Best Selenium code snippet using org.openqa.selenium.internal.Either.isLeft
Source:LocalDistributor.java
...422 result = Either.left(e);423 } catch (RuntimeException e) {424 result = Either.left(new SessionNotCreatedException(e.getMessage(), e));425 }426 if (result.isLeft()) {427 WebDriverException exception = result.left();428 if (exception instanceof SessionNotCreatedException) {429 throw exception;430 }431 throw new SessionNotCreatedException(exception.getMessage(), exception);432 }433 return result.right();434 }435 private SlotId reserveSlot(RequestId requestId, Capabilities caps) {436 Lock writeLock = lock.writeLock();437 writeLock.lock();438 try {439 Set<SlotId> slotIds = slotSelector.selectSlot(caps, getAvailableNodes());440 if (slotIds.isEmpty()) {441 LOG.log(442 getDebugLogLevel(),443 String.format("No slots found for request %s and capabilities %s", requestId, caps));444 return null;445 }446 for (SlotId slotId : slotIds) {447 if (reserve(slotId)) {448 return slotId;449 }450 }451 return null;452 } finally {453 writeLock.unlock();454 }455 }456 private boolean isSupported(Capabilities caps) {457 return getAvailableNodes().stream().anyMatch(node -> node.hasCapability(caps));458 }459 private boolean reserve(SlotId id) {460 Require.nonNull("Slot ID", id);461 Lock writeLock = this.lock.writeLock();462 writeLock.lock();463 try {464 Node node = nodes.get(id.getOwningNodeId());465 if (node == null) {466 LOG.log(getDebugLogLevel(), String.format("Unable to find node with id %s", id));467 return false;468 }469 return model.reserve(id);470 } finally {471 writeLock.unlock();472 }473 }474 public void callExecutorShutdown() {475 LOG.info("Shutting down Distributor executor service");476 regularly.shutdown();477 }478 public class NewSessionRunnable implements Runnable {479 @Override480 public void run() {481 List<SessionRequestCapability> queueContents = sessionQueue.getQueueContents();482 if (rejectUnsupportedCaps) {483 checkMatchingSlot(queueContents);484 }485 int initialSize = queueContents.size();486 boolean retry = initialSize != 0;487 while (retry) {488 // We deliberately run this outside of a lock: if we're unsuccessful489 // starting the session, we just put the request back on the queue.490 // This does mean, however, that under high contention, we might end491 // up starving a session request.492 Set<Capabilities> stereotypes =493 getAvailableNodes().stream()494 .filter(NodeStatus::hasCapacity)495 .map(496 node ->497 node.getSlots().stream()498 .map(Slot::getStereotype)499 .collect(Collectors.toSet()))500 .flatMap(Collection::stream)501 .collect(Collectors.toSet());502 Optional<SessionRequest> maybeRequest = sessionQueue.getNextAvailable(stereotypes);503 maybeRequest.ifPresent(this::handleNewSessionRequest);504 int currentSize = sessionQueue.getQueueContents().size();505 retry = currentSize != 0 && currentSize != initialSize;506 initialSize = currentSize;507 }508 }509 private void checkMatchingSlot(List<SessionRequestCapability> sessionRequests) {510 for(SessionRequestCapability request : sessionRequests) {511 long unmatchableCount = request.getDesiredCapabilities().stream()512 .filter(caps -> !isSupported(caps))513 .count();514 if (unmatchableCount == request.getDesiredCapabilities().size()) {515 SessionNotCreatedException exception = new SessionNotCreatedException(516 "No nodes support the capabilities in the request");517 sessionQueue.complete(request.getRequestId(), Either.left(exception));518 }519 }520 }521 private void handleNewSessionRequest(SessionRequest sessionRequest) {522 RequestId reqId = sessionRequest.getRequestId();523 try (Span span = TraceSessionRequest.extract(tracer, sessionRequest).createSpan("distributor.poll_queue")) {524 Map<String, EventAttributeValue> attributeMap = new HashMap<>();525 attributeMap.put(526 AttributeKey.LOGGER_CLASS.getKey(),527 EventAttribute.setValue(getClass().getName()));528 span.setAttribute(AttributeKey.REQUEST_ID.getKey(), reqId.toString());529 attributeMap.put(530 AttributeKey.REQUEST_ID.getKey(),531 EventAttribute.setValue(reqId.toString()));532 attributeMap.put("request", EventAttribute.setValue(sessionRequest.toString()));533 Either<SessionNotCreatedException, CreateSessionResponse> response = newSession(sessionRequest);534 if (response.isLeft() && response.left() instanceof RetrySessionRequestException) {535 try(Span childSpan = span.createSpan("distributor.retry")) {536 LOG.info("Retrying");537 boolean retried = sessionQueue.retryAddToQueue(sessionRequest);538 attributeMap.put("request.retry_add", EventAttribute.setValue(retried));539 childSpan.addEvent("Retry adding to front of queue. No slot available.", attributeMap);540 if (retried) {541 return;542 }543 childSpan.addEvent("retrying_request", attributeMap);544 }545 }546 sessionQueue.complete(reqId, response);547 }548 }...
Source:NodeTest.java
...138 registrationSecret,139 ImmutableSet.of());140 Either<WebDriverException, CreateSessionResponse> response = node.newSession(141 createSessionRequest(caps));142 assertThatEither(response).isLeft();143 }144 @Test145 public void shouldCreateASessionIfTheCorrectCapabilitiesArePassedToIt() {146 Either<WebDriverException, CreateSessionResponse> response = node.newSession(createSessionRequest(caps));147 assertThatEither(response).isRight();148 CreateSessionResponse sessionResponse = response.right();149 assertThat(sessionResponse.getSession()).isNotNull();150 }151 @Test152 public void shouldRetryIfNoMatchingSlotIsAvailable() {153 Node local = LocalNode.builder(tracer, bus, uri, uri, registrationSecret)154 .add(caps, new SessionFactory() {155 @Override156 public Either<WebDriverException, ActiveSession> apply(157 CreateSessionRequest createSessionRequest) {158 return Either.left(new SessionNotCreatedException("HelperFactory for testing"));159 }160 @Override161 public boolean test(Capabilities capabilities) {162 return false;163 }164 })165 .build();166 HttpClient.Factory clientFactory = new PassthroughHttpClient.Factory(local);167 Node node = new RemoteNode(168 tracer,169 clientFactory,170 new NodeId(UUID.randomUUID()),171 uri,172 registrationSecret,173 ImmutableSet.of(caps));174 ImmutableCapabilities wrongCaps = new ImmutableCapabilities("browserName", "burger");175 Either<WebDriverException, CreateSessionResponse> sessionResponse = node.newSession(createSessionRequest(wrongCaps));176 assertThatEither(sessionResponse).isLeft();177 assertThat(sessionResponse.left()).isInstanceOf(RetrySessionRequestException.class);178 }179 @Test180 public void shouldOnlyCreateAsManySessionsAsFactories() {181 Node node = LocalNode.builder(tracer, bus, uri, uri, registrationSecret)182 .add(caps, new TestSessionFactory((id, c) -> new Session(id, uri, stereotype, c, Instant.now())))183 .build();184 Either<WebDriverException, CreateSessionResponse> response =185 node.newSession(createSessionRequest(caps));186 assertThatEither(response).isRight();187 Session session = response.right().getSession();188 assertThat(session).isNotNull();189 Either<WebDriverException, CreateSessionResponse> secondSession =190 node.newSession(createSessionRequest(caps));191 assertThatEither(secondSession).isLeft();192 }193 @Test194 public void willRefuseToCreateMoreSessionsThanTheMaxSessionCount() {195 Either<WebDriverException, CreateSessionResponse> response = node.newSession(createSessionRequest(caps));196 assertThatEither(response).isRight();197 response = node.newSession(createSessionRequest(caps));198 assertThatEither(response).isRight();199 response = node.newSession(createSessionRequest(caps));200 assertThatEither(response).isLeft();201 }202 @Test203 public void stoppingASessionReducesTheNumberOfCurrentlyActiveSessions() {204 assertThat(local.getCurrentSessionCount()).isEqualTo(0);205 Either<WebDriverException, CreateSessionResponse> response = local.newSession(createSessionRequest(caps));206 assertThatEither(response).isRight();207 Session session = response.right().getSession();208 assertThat(local.getCurrentSessionCount()).isEqualTo(1);209 local.stop(session.getId());210 assertThat(local.getCurrentSessionCount()).isEqualTo(0);211 }212 @Test213 public void sessionsThatAreStoppedWillNotBeReturned() {214 Either<WebDriverException, CreateSessionResponse> response = node.newSession(createSessionRequest(caps));215 assertThatEither(response).isRight();216 Session expected = response.right().getSession();217 node.stop(expected.getId());218 assertThatExceptionOfType(NoSuchSessionException.class)219 .isThrownBy(() -> local.getSession(expected.getId()));220 assertThatExceptionOfType(NoSuchSessionException.class)221 .isThrownBy(() -> node.getSession(expected.getId()));222 }223 @Test224 public void stoppingASessionThatDoesNotExistWillThrowAnException() {225 assertThatExceptionOfType(NoSuchSessionException.class)226 .isThrownBy(() -> local.stop(new SessionId(UUID.randomUUID())));227 assertThatExceptionOfType(NoSuchSessionException.class)228 .isThrownBy(() -> node.stop(new SessionId(UUID.randomUUID())));229 }230 @Test231 public void attemptingToGetASessionThatDoesNotExistWillCauseAnExceptionToBeThrown() {232 assertThatExceptionOfType(NoSuchSessionException.class)233 .isThrownBy(() -> local.getSession(new SessionId(UUID.randomUUID())));234 assertThatExceptionOfType(NoSuchSessionException.class)235 .isThrownBy(() -> node.getSession(new SessionId(UUID.randomUUID())));236 }237 @Test238 public void willRespondToWebDriverCommandsSentToOwnedSessions() {239 AtomicBoolean called = new AtomicBoolean(false);240 class Recording extends Session implements HttpHandler {241 private Recording() {242 super(new SessionId(UUID.randomUUID()), uri, stereotype, caps, Instant.now());243 }244 @Override245 public HttpResponse execute(HttpRequest req) throws UncheckedIOException {246 called.set(true);247 return new HttpResponse();248 }249 }250 Node local = LocalNode.builder(tracer, bus, uri, uri, registrationSecret)251 .add(caps, new TestSessionFactory((id, c) -> new Recording()))252 .build();253 Node remote = new RemoteNode(254 tracer,255 new PassthroughHttpClient.Factory(local),256 new NodeId(UUID.randomUUID()),257 uri,258 registrationSecret,259 ImmutableSet.of(caps));260 Either<WebDriverException, CreateSessionResponse> response =261 remote.newSession(createSessionRequest(caps));262 assertThatEither(response).isRight();263 Session session = response.right().getSession();264 HttpRequest req = new HttpRequest(POST, String.format("/session/%s/url", session.getId()));265 remote.execute(req);266 assertThat(called.get()).isTrue();267 }268 @Test269 public void shouldOnlyRespondToWebDriverCommandsForSessionsTheNodeOwns() {270 Either<WebDriverException, CreateSessionResponse> response =271 node.newSession(createSessionRequest(caps));272 assertThatEither(response).isRight();273 Session session = response.right().getSession();274 HttpRequest req = new HttpRequest(POST, String.format("/session/%s/url", session.getId()));275 assertThat(local.matches(req)).isTrue();276 assertThat(node.matches(req)).isTrue();277 req = new HttpRequest(POST, String.format("/session/%s/url", UUID.randomUUID()));278 assertThat(local.matches(req)).isFalse();279 assertThat(node.matches(req)).isFalse();280 }281 @Test282 public void aSessionThatTimesOutWillBeStoppedAndRemovedFromTheSessionMap() {283 AtomicReference<Instant> now = new AtomicReference<>(Instant.now());284 Clock clock = new MyClock(now);285 Node node = LocalNode.builder(tracer, bus, uri, uri, registrationSecret)286 .add(caps, new TestSessionFactory((id, c) -> new Session(id, uri, stereotype, c, Instant.now())))287 .sessionTimeout(Duration.ofMinutes(3))288 .advanced()289 .clock(clock)290 .build();291 Either<WebDriverException, CreateSessionResponse> response =292 node.newSession(createSessionRequest(caps));293 assertThatEither(response).isRight();294 Session session = response.right().getSession();295 now.set(now.get().plus(Duration.ofMinutes(5)));296 assertThatExceptionOfType(NoSuchSessionException.class)297 .isThrownBy(() -> node.getSession(session.getId()));298 }299 @Test300 public void shouldNotPropagateExceptionsWhenSessionCreationFails() {301 Node local = LocalNode.builder(tracer, bus, uri, uri, registrationSecret)302 .add(caps, new TestSessionFactory((id, c) -> {303 throw new SessionNotCreatedException("eeek");304 }))305 .build();306 Either<WebDriverException, CreateSessionResponse> response =307 local.newSession(createSessionRequest(caps));308 assertThatEither(response).isLeft();309 }310 @Test311 public void eachSessionShouldReportTheNodesUrl() throws URISyntaxException {312 URI sessionUri = new URI("http://cheese:42/peas");313 Node node = LocalNode.builder(tracer, bus, uri, uri, registrationSecret)314 .add(caps, new TestSessionFactory((id, c) -> new Session(id, sessionUri, stereotype, c, Instant.now())))315 .build();316 Either<WebDriverException, CreateSessionResponse> response =317 node.newSession(createSessionRequest(caps));318 assertThatEither(response).isRight();319 Session session = response.right().getSession();320 assertThat(session).isNotNull();321 assertThat(session.getUri()).isEqualTo(uri);322 }323 @Test324 public void quittingASessionShouldCauseASessionClosedEventToBeFired() {325 AtomicReference<Object> obj = new AtomicReference<>();326 bus.addListener(SessionClosedEvent.listener(obj::set));327 Either<WebDriverException, CreateSessionResponse> response =328 node.newSession(createSessionRequest(caps));329 assertThatEither(response).isRight();330 Session session = response.right().getSession();331 node.stop(session.getId());332 // Because we're using the event bus, we can't expect the event to fire instantly. We're using333 // an inproc bus, so in reality it's reasonable to expect the event to fire synchronously, but334 // let's play it safe.335 Wait<AtomicReference<Object>> wait = new FluentWait<>(obj).withTimeout(ofSeconds(2));336 wait.until(ref -> ref.get() != null);337 }338 @Test339 public void canReturnStatus() {340 Either<WebDriverException, CreateSessionResponse> response =341 node.newSession(createSessionRequest(caps));342 assertThatEither(response).isRight();343 HttpRequest req = new HttpRequest(GET, "/status");344 HttpResponse res = node.execute(req);345 assertThat(res.getStatus()).isEqualTo(200);346 NodeStatus seen = null;347 try (JsonInput input = new Json().newInput(Contents.reader(res))) {348 input.beginObject();349 while (input.hasNext()) {350 switch (input.nextName()) {351 case "value":352 input.beginObject();353 while (input.hasNext()) {354 switch (input.nextName()) {355 case "node":356 seen = input.read(NodeStatus.class);357 break;358 default:359 input.skipValue();360 }361 }362 input.endObject();363 break;364 default:365 input.skipValue();366 break;367 }368 }369 }370 NodeStatus expected = node.getStatus();371 assertThat(seen).isEqualTo(expected);372 }373 @Test374 public void returns404ForAnUnknownCommand() {375 HttpRequest req = new HttpRequest(GET, "/foo");376 HttpResponse res = node.execute(req);377 assertThat(res.getStatus()).isEqualTo(404);378 Map<String, Object> content = new Json().toType(string(res), MAP_TYPE);379 assertThat(content).containsOnlyKeys("value")380 .extracting("value").asInstanceOf(MAP)381 .containsEntry("error", "unknown command")382 .containsEntry("message", "Unable to find handler for (GET) /foo");383 }384 @Test385 public void canUploadAFile() throws IOException {386 Either<WebDriverException, CreateSessionResponse> response =387 node.newSession(createSessionRequest(caps));388 assertThatEither(response).isRight();389 Session session = response.right().getSession();390 HttpRequest req = new HttpRequest(POST, String.format("/session/%s/file", session.getId()));391 String hello = "Hello, world!";392 String zip = Zip.zip(createTmpFile(hello));393 String payload = new Json().toJson(Collections.singletonMap("file", zip));394 req.setContent(() -> new ByteArrayInputStream(payload.getBytes()));395 node.execute(req);396 File baseDir = getTemporaryFilesystemBaseDir(local.getTemporaryFilesystem(session.getId()));397 assertThat(baseDir.listFiles()).hasSize(1);398 File uploadDir = baseDir.listFiles()[0];399 assertThat(uploadDir.listFiles()).hasSize(1);400 assertThat(new String(Files.readAllBytes(uploadDir.listFiles()[0].toPath()))).isEqualTo(hello);401 node.stop(session.getId());402 assertThat(baseDir).doesNotExist();403 }404 @Test405 public void shouldNotCreateSessionIfDraining() {406 node.drain();407 assertThat(local.isDraining()).isTrue();408 assertThat(node.isDraining()).isTrue();409 Either<WebDriverException, CreateSessionResponse> sessionResponse = node.newSession(createSessionRequest(caps));410 assertThatEither(sessionResponse).isLeft();411 }412 @Test413 public void shouldNotShutdownDuringOngoingSessionsIfDraining() throws InterruptedException {414 Either<WebDriverException, CreateSessionResponse> firstResponse =415 node.newSession(createSessionRequest(caps));416 assertThatEither(firstResponse).isRight();417 Session firstSession = firstResponse.right().getSession();418 Either<WebDriverException, CreateSessionResponse> secondResponse =419 node.newSession(createSessionRequest(caps));420 assertThatEither(secondResponse).isRight();421 Session secondSession = secondResponse.right().getSession();422 CountDownLatch latch = new CountDownLatch(1);423 bus.addListener(NodeDrainComplete.listener(ignored -> latch.countDown()));424 node.drain();425 assertThat(local.isDraining()).isTrue();426 assertThat(node.isDraining()).isTrue();427 Either<WebDriverException, CreateSessionResponse> thirdResponse = node.newSession(createSessionRequest(caps));428 assertThatEither(thirdResponse).isLeft();429 assertThat(firstSession).isNotNull();430 assertThat(secondSession).isNotNull();431 assertThat(local.getCurrentSessionCount()).isEqualTo(2);432 latch.await(1, SECONDS);433 assertThat(latch.getCount()).isEqualTo(1);434 }435 @Test436 public void shouldShutdownAfterSessionsCompleteIfDraining() throws InterruptedException {437 CountDownLatch latch = new CountDownLatch(1);438 bus.addListener(NodeDrainComplete.listener(ignored -> latch.countDown()));439 Either<WebDriverException, CreateSessionResponse> firstResponse =440 node.newSession(createSessionRequest(caps));441 assertThatEither(firstResponse).isRight();442 Session firstSession = firstResponse.right().getSession();...
Source:LocalNewSessionQueue.java
...304 contexts.remove(reqId);305 } finally {306 writeLock.unlock();307 }308 if (result.isLeft()) {309 bus.fire(new NewSessionRejectedEvent(new NewSessionErrorResponse(reqId, result.left().getMessage())));310 }311 data.setResult(result);312 }313 }314 @Override315 public int clearQueue() {316 Lock writeLock = lock.writeLock();317 writeLock.lock();318 try {319 int size = queue.size();320 queue.clear();321 requests.forEach((reqId, data) -> {322 data.setResult(Either.left(new SessionNotCreatedException("Request queue was cleared")));...
Source:LocalNodeTest.java
...119 new CreateSessionRequest(120 ImmutableSet.of(W3C),121 stereotype,122 ImmutableMap.of()));123 assertThatEither(sessionResponse).isLeft();124 assertThat(sessionResponse.left()).isInstanceOf(RetrySessionRequestException.class);125 }126 @Test127 public void cannotCreateNewSessionsOnMaxSessionCount() {128 Capabilities stereotype = new ImmutableCapabilities("cheese", "brie");129 Either<WebDriverException, CreateSessionResponse> sessionResponse = node.newSession(130 new CreateSessionRequest(131 ImmutableSet.of(W3C),132 stereotype,133 ImmutableMap.of()));134 assertThatEither(sessionResponse).isLeft();135 assertThat(sessionResponse.left()).isInstanceOf(RetrySessionRequestException.class);136 }137 @Test138 public void canReturnStatusInfo() {139 NodeStatus status = node.getStatus();140 assertThat(status.getSlots().stream()141 .filter(slot -> slot.getSession().isPresent())142 .map(slot -> slot.getSession().get())143 .filter(s -> s.getId().equals(session.getId()))).isNotEmpty();144 node.stop(session.getId());145 status = node.getStatus();146 assertThat(status.getSlots().stream()147 .filter(slot -> slot.getSession().isPresent())148 .map(slot -> slot.getSession().get())...
Source:DriverServiceSessionFactoryTest.java
...72 public void shouldNotInstantiateSessionIfNoDialectSpecifiedInARequest() {73 DriverServiceSessionFactory factory = factoryFor("chrome", builder);74 Either<WebDriverException, ActiveSession> session = factory.apply(new CreateSessionRequest(75 ImmutableSet.of(), toPayload("chrome"), ImmutableMap.of()));76 assertThat(session.isLeft()).isTrue();77 verifyNoInteractions(builder);78 }79 @Test80 public void shouldNotInstantiateSessionIfCapabilitiesDoNotMatch() {81 DriverServiceSessionFactory factory = factoryFor("chrome", builder);82 Either<WebDriverException, ActiveSession> session = factory.apply(new CreateSessionRequest(83 ImmutableSet.of(Dialect.W3C), toPayload("firefox"), ImmutableMap.of()));84 assertThat(session.isLeft()).isTrue();85 verifyNoInteractions(builder);86 }87 @Test88 public void shouldNotInstantiateSessionIfBuilderCanNotBuildService() {89 when(builder.build()).thenThrow(new WebDriverException());90 DriverServiceSessionFactory factory = factoryFor("chrome", builder);91 Either<WebDriverException, ActiveSession> session = factory.apply(new CreateSessionRequest(92 ImmutableSet.of(Dialect.W3C), toPayload("chrome"), ImmutableMap.of()));93 assertThat(session.isLeft()).isTrue();94 verify(builder, times(1)).build();95 verifyNoMoreInteractions(builder);96 }97 @Test98 public void shouldNotInstantiateSessionIfRemoteEndReturnsInvalidResponse() throws IOException {99 HttpClient httpClient = mock(HttpClient.class);100 when(httpClient.execute(any(HttpRequest.class))).thenReturn(101 new HttpResponse().setStatus(200).setContent(() -> new ByteArrayInputStream(102 "Hello, world!".getBytes())));103 when(clientFactory.createClient(any(URL.class))).thenReturn(httpClient);104 DriverServiceSessionFactory factory = factoryFor("chrome", builder);105 Either<WebDriverException, ActiveSession> session = factory.apply(new CreateSessionRequest(106 ImmutableSet.of(Dialect.W3C), toPayload("chrome"), ImmutableMap.of()));107 assertThat(session.isLeft()).isTrue();108 verify(builder, times(1)).build();109 verifyNoMoreInteractions(builder);110 verify(driverService, times(1)).start();111 verify(driverService, atLeastOnce()).getUrl();112 verify(driverService, times(1)).stop();113 verifyNoMoreInteractions(driverService);114 }115 @Test116 public void shouldInstantiateSessionIfEverythingIsOK() throws IOException {117 HttpClient httpClient = mock(HttpClient.class);118 when(httpClient.execute(any(HttpRequest.class))).thenReturn(119 new HttpResponse().setStatus(200).setContent(() -> new ByteArrayInputStream(120 "{ \"value\": { \"sessionId\": \"1\", \"capabilities\": {} } }".getBytes())));121 when(clientFactory.createClient(any(URL.class))).thenReturn(httpClient);...
Source:CreateSession.java
...38 SessionRequest request = Contents.fromJson(req, SessionRequest.class);39 Either<SessionNotCreatedException, CreateSessionResponse> result = distributor.newSession(request);40 HttpResponse res = new HttpResponse();41 Map<String, Object> value;42 if (result.isLeft()) {43 res.setStatus(HTTP_INTERNAL_ERROR);44 value = singletonMap("value", result.left());45 } else {46 value = singletonMap("value", result.right());47 }48 res.setContent(Contents.asJson(value));49 return res;50 }51}...
Source:Either.java
...31 }32 public static <A, B> Either<A, B> right(B b) {33 return new Either<>(null, b);34 }35 public boolean isLeft() {36 return left != null;37 }38 public boolean isRight() {39 return right != null;40 }41 public A left() {42 return left;43 }44 public B right() {45 return right;46 }47 public <R> R map(Function<? super B, ? extends R> mapper) {48 Require.nonNull("Mapper", mapper);49 return mapper.apply(right());50 }51 public <R> R mapLeft(Function<? super A, ? extends R> mapper) {52 Require.nonNull("Mapper", mapper);53 return mapper.apply(left());54 }55 @Override56 public Iterator<B> iterator() {57 return Collections.singleton(right()).iterator();58 }59 public Stream<B> stream() {60 return Stream.of(right());61 }62 @Override63 public String toString() {64 return "[Either(" + (isLeft() ? "left" : "right") + "): " + (isLeft() ? left() : right()) + "]";65 }66}...
Source:EitherAssert.java
...4public class EitherAssert<A, B> extends AbstractAssert<EitherAssert<A, B>, Either<A, B>> {5 public EitherAssert(Either<A, B> actual) {6 super(actual, EitherAssert.class);7 }8 public EitherAssert<A, B> isLeft() {9 isNotNull();10 if (actual.isRight()) {11 failWithMessage(12 "Expected Either to be left but it is right: %s", actual.right());13 }14 return this;15 }16 public EitherAssert<A, B> isRight() {17 isNotNull();18 if (actual.isLeft()) {19 failWithMessage(20 "Expected Either to be right but it is left: %s", actual.left());21 }22 return this;23 }24}...
isLeft
Using AI Code Generation
1import org.openqa.selenium.internal.Either;2public class EitherExample {3public static void main(String[] args) {4Either<Integer, String> either = Either.left(5);5System.out.println(either.isLeft());6System.out.println(either.isRight());7}8}9isRight() method of Either class10public boolean isRight()11import org.openqa.selenium.internal.Either;12public class EitherExample {13public static void main(String[] args) {14Either<Integer, String> either = Either.right(“Right value”);15System.out.println(either.isLeft());16System.out.println(either.isRight());17}18}19left() method of Either class20public T left()21import org.openqa.selenium.internal.Either;22public class EitherExample {23public static void main(String[] args) {24Either<Integer, String> either = Either.left(5);25System.out.println(either.left());26}27}28right() method of Either class29public U right()30import org.openqa.selenium.internal.Either;31public class EitherExample {32public static void main(String[] args) {33Either<Integer, String> either = Either.right(“Right value”);34System.out.println(either.right());35}36}37toString() method of Either class
isLeft
Using AI Code Generation
1import org.openqa.selenium.By;2import org.openqa.selenium.WebDriver;3import org.openqa.selenium.WebElement;4import org.openqa.selenium.chrome.ChromeDriver;5import org.openqa.selenium.internal.Either;6public class Selenium4Features {7 public static void main(String[] args) {8 System.setProperty("webdriver.chrome.driver", "C:\\Users\\Dell\\Desktop\\chromedriver.exe");9 WebDriver driver = new ChromeDriver();10 driver.manage().window().maximize();11 WebElement element = driver.findElement(By.name("q"));12 Either<WebElement, Boolean> either = element.isDisplayed();13 if(either.isLeft()) {14 System.out.println("Element is available");15 }else {16 System.out.println("Element is not available");17 }18 }19}20import org.openqa.selenium.By;21import org.openqa.selenium.WebDriver;22import org.openqa.selenium.WebElement;23import org.openqa.selenium.chrome.ChromeDriver;24import org.openqa.selenium.interactions.Actions;25public class Selenium4Features {26 public static void main(String[] args) {27 System.setProperty("webdriver.chrome.driver", "C:\\Users\\Dell\\Desktop\\chromedriver.exe");28 WebDriver driver = new ChromeDriver();29 driver.manage().window().maximize();30 WebElement source = driver.findElement(By.id("draggable"));31 WebElement target = driver.findElement(By.id("droppable"));32 Actions actions = new Actions(driver);33 actions.dragAndDrop(source, target).perform();34 }35}
isLeft
Using AI Code Generation
1package com.example.tests;2import static org.junit.Assert.*;3import org.junit.Test;4import org.openqa.selenium.internal.Either;5public class EitherTest {6 public void testEither() {7 Either<String, Integer> left = Either.left("left");8 Either<String, Integer> right = Either.right(1);9 assertTrue(left.isLeft());10 assertTrue(right.isRight());11 }12}13package com.example.tests;14import static org.junit.Assert.*;15import org.junit.Test;16import org.openqa.selenium.internal.Either;17public class EitherTest {18 public void testEither() {19 Either<String, Integer> left = Either.left("left");20 Either<String, Integer> right = Either.right(1);21 assertTrue(right.isRight());22 assertTrue(left.isLeft());23 }24}25package com.example.tests;26import static org.junit.Assert.*;27import org.junit.Test;28import org.openqa.selenium.internal.Either;29public class EitherTest {30 public void testEither() {31 Either<String, Integer> left = Either.left("left");32 Either<String, Integer> right = Either.right(1);33 assertEquals("left", left.left());34 assertEquals(new Integer(1), right.right());35 }36}37package com.example.tests;38import static org.junit.Assert.*;39import org.junit.Test;40import org.openqa.selenium.internal.Either;41public class EitherTest {42 public void testEither() {43 Either<String, Integer> left = Either.left("left");44 Either<String, Integer> right = Either.right(1);45 assertEquals(new Integer(1), right.right());46 assertEquals("left", left.left());47 }48}49package com.example.tests;50import static org.junit.Assert.*;51import org.junit.Test;52import org.openqa.selenium.internal.Either;53public class EitherTest {54 public void testEither() {55 Either<String, Integer> left = Either.left("left");56 Either<String, Integer> right = Either.right(1);57 assertEquals("Either{left=left}", left.toString());58 assertEquals("Either{right=1}", right.toString());59 }60}
isLeft
Using AI Code Generation
1import org.openqa.selenium.internal.Either2import org.openqa.selenium.WebDriver3import org.openqa.selenium.By4import org.openqa.selenium.WebElement5import org.openqa.selenium.support.ui.ExpectedConditions6import org.openqa.selenium.support.ui.WebDriverWait7import org.openqa.selenium.chrome.ChromeDriver8import org.openqa.selenium.chrome.ChromeOptions9import groovy.json.JsonSlurper10def setup() {11 ChromeOptions options = new ChromeOptions()12 options.addArguments("--headless")13 options.addArguments("--disable-gpu")14 options.addArguments("--window-size=1024,768")15 options.addArguments("--no-sandbox")16 options.addArguments("--disable-dev-shm-usage")17 options.addArguments("--ignore-certificate-errors")18 options.addArguments("--silent")19 System.setProperty("webdriver.chrome.driver", "/usr/bin/chromedriver")20 driver = new ChromeDriver(options)21 wait = new WebDriverWait(driver, 10)22}23def teardown() {24 if (driver) {25 driver.quit()26 }27}28def createDriver() {29 return new ChromeDriver()30}31def getDriver() {32}33def getWait() {34}35def getWaitTime() {36}37def getJsonSlurper() {38 return new JsonSlurper()39}40def getJsonFromJsonSlurper(jsonSlurper, json) {41 return jsonSlurper.parseText(json)42}43def getJsonFromJsonSlurper(jsonSlurper, json, path) {44 return jsonSlurper.parseText(json, path)45}46def getJsonFromJsonSlurper(jsonSlurper, json, path, strict) {47 return jsonSlurper.parseText(json, path, strict)48}49def getJsonFromJsonSlurper(jsonSlurper, json, path, strict, classType) {50 return jsonSlurper.parseText(json, path, strict, classType)51}52def getJsonFromJsonSlurper(jsonSlurper, json, path, strict, classType, useConstructor) {53 return jsonSlurper.parseText(json, path, strict, classType, useConstructor)54}
isLeft
Using AI Code Generation
1 public boolean isElementPresent(By by) {2 try {3 driver.findElement(by);4 return true;5 } catch (NoSuchElementException e) {6 return false;7 }8 }9 public boolean isElementPresent(By by) {10 try {11 driver.findElement(by);12 return true;13 } catch (NoSuchElementException e) {14 return false;15 }16 }17 public boolean isElementPresent(By by) {18 try {19 driver.findElement(by);20 return true;21 } catch (NoSuchElementException e) {22 return false;23 }24 }25 public boolean isElementPresent(By by) {26 try {27 driver.findElement(by);28 return true;29 } catch (NoSuchElementException e) {30 return false;31 }32 }33 public boolean isElementPresent(By by) {34 try {35 driver.findElement(by);36 return true;37 } catch (NoSuchElementException e) {38 return false;39 }40 }41 public boolean isElementPresent(By by) {42 try {43 driver.findElement(by);44 return true;45 } catch (NoSuchElementException e) {
isLeft
Using AI Code Generation
1} else {2 System.out.println("Element is not displayed");3}4} else {5 System.out.println("Element is not displayed");6}
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!!