Best Selenium code snippet using org.openqa.selenium.grid.node.Node.matches
Source:KubernetesNode.java  
...266    public int getCurrentSessionCount() {267        return Math.toIntExact(currentSessions.size());268    }269    @Override270    public boolean matches(HttpRequest req) {271        return additionalRoutes.matches(req) || super.matches(req);272    }273    @Override274    public HttpResponse execute(HttpRequest req) {275        return additionalRoutes.matches(req) ? additionalRoutes.execute(req) : super.execute(req);276    }277    SessionId sessionIdFrom(Map<String, String> params) {278        return new SessionId(params.get("sessionId"));279    }280    String fileNameFrom(Map<String, String> params) {281        return params.get("fileName");282    }283    private KubernetesSession getActiveSession(SessionId id) {284        return (KubernetesSession) getSessionSlot(id).getSession();285    }286    private void stopAllSessions() {287        if (currentSessions.size() > 0) {288            LOG.info("Trying to stop all running sessions before shutting down...");289            currentSessions.invalidateAll();...Source:NodeTest.java  
...203    Session session = node.newSession(createSessionRequest(caps))204        .map(CreateSessionResponse::getSession)205        .orElseThrow(() -> new RuntimeException("Session not created"));206    HttpRequest req = new HttpRequest(POST, String.format("/session/%s/url", session.getId()));207    assertThat(local.matches(req)).isTrue();208    assertThat(node.matches(req)).isTrue();209    req = new HttpRequest(POST, String.format("/session/%s/url", UUID.randomUUID()));210    assertThat(local.matches(req)).isFalse();211    assertThat(node.matches(req)).isFalse();212  }213  @Test214  public void aSessionThatTimesOutWillBeStoppedAndRemovedFromTheSessionMap() {215    AtomicReference<Instant> now = new AtomicReference<>(Instant.now());216    Clock clock = new MyClock(now);217    Node node = LocalNode.builder(tracer, bus, clientFactory, uri, null)218        .add(caps, new TestSessionFactory((id, c) -> new Session(id, uri, c)))219        .sessionTimeout(Duration.ofMinutes(3))220        .advanced()221        .clock(clock)222        .build();223    Session session = node.newSession(createSessionRequest(caps))224        .map(CreateSessionResponse::getSession)225        .orElseThrow(() -> new RuntimeException("Session not created"));...Source:CustomLocatorHandlerTest.java  
...145  @Test146  public void shouldBeAbleToUseNodeAsWebDriver() {147    String elementId = UUID.randomUUID().toString();148    Node node = Mockito.mock(Node.class);149    when(node.executeWebDriverCommand(argThat(matchesUri("/session/{sessionId}/elements"))))150      .thenReturn(151        new HttpResponse()152          .addHeader("Content-Type", Json.JSON_UTF_8)153          .setContent(Contents.asJson(singletonMap(154            "value", singletonList(singletonMap(Dialect.W3C.getEncodedElementKey(), elementId))))));155    HttpHandler handler = new CustomLocatorHandler(156      node,157      registrationSecret,158      singleton(new CustomLocator() {159        @Override160        public String getLocatorName() {161          return "cheese";162        }163        @Override164        public By createBy(Object usingParameter) {165          return By.id("brie");166        }167      }));168    HttpResponse res = handler.execute(169      new HttpRequest(POST, "/session/1234/elements")170        .setContent(Contents.asJson(ImmutableMap.of(171          "using", "cheese",172          "value", "tasty"))));173    List<Map<String, Object>> elements = Values.get(res, new TypeToken<List<Map<String, Object>>>(){}.getType());174    assertThat(elements).hasSize(1);175    Object seenId = elements.get(0).get(Dialect.W3C.getEncodedElementKey());176    assertThat(seenId).isEqualTo(elementId);177  }178  @Test179  public void shouldBeAbleToRootASearchWithinAnElement() {180    String elementId = UUID.randomUUID().toString();181    Node node = Mockito.mock(Node.class);182    when(node.executeWebDriverCommand(argThat(matchesUri("/session/{sessionId}/element/{elementId}/element"))))183      .thenReturn(184        new HttpResponse()185          .addHeader("Content-Type", Json.JSON_UTF_8)186          .setContent(Contents.asJson(singletonMap(187            "value", singletonList(singletonMap(Dialect.W3C.getEncodedElementKey(), elementId))))));188    HttpHandler handler = new CustomLocatorHandler(189      node,190      registrationSecret,191      singleton(new CustomLocator() {192        @Override193        public String getLocatorName() {194          return "cheese";195        }196        @Override197        public By createBy(Object usingParameter) {198          return By.id("brie");199        }200      }));201    HttpResponse res = handler.execute(202      new HttpRequest(POST, "/session/1234/element/234345/elements")203        .setContent(Contents.asJson(ImmutableMap.of(204          "using", "cheese",205          "value", "tasty"))));206    List<Map<String, Object>> elements = Values.get(res, new TypeToken<List<Map<String, Object>>>(){}.getType());207    assertThat(elements).hasSize(1);208    Object seenId = elements.get(0).get(Dialect.W3C.getEncodedElementKey());209    assertThat(seenId).isEqualTo(elementId);210  }211  @Test212  public void shouldNotFindLocatorStrategyForId() {213    Capabilities caps = new ImmutableCapabilities("browserName", "cheesefox");214    Node node = nodeBuilder.add(215      caps,216      new TestSessionFactory((id, c) -> new Session(id, nodeUri, caps, c, Instant.now())))217      .build();218    HttpHandler handler = new CustomLocatorHandler(node, registrationSecret, emptySet());219    HttpResponse res = handler.with(new ErrorFilter()).execute(220      new HttpRequest(POST, "/session/1234/element")221        .setContent(Contents.asJson(ImmutableMap.of(222          "using", "id",223          "value", "tasty"))));224    assertThatExceptionOfType(InvalidArgumentException.class).isThrownBy(() -> Values.get(res, WebElement.class));225  }226  @Test227  public void shouldFallbackToUseById() {228    String elementId = UUID.randomUUID().toString();229    Node node = Mockito.mock(Node.class);230    when(node.executeWebDriverCommand(argThat(matchesUri("/session/{sessionId}/elements"))))231      .thenReturn(232        new HttpResponse()233          .addHeader("Content-Type", Json.JSON_UTF_8)234          .setContent(Contents.asJson(singletonMap(235            "value", singletonList(singletonMap(Dialect.W3C.getEncodedElementKey(), elementId))))));236    HttpHandler handler = new CustomLocatorHandler(237      node,238      registrationSecret,239      singleton(new ById()));240    HttpResponse res = handler.execute(241      new HttpRequest(POST, "/session/1234/elements")242        .setContent(Contents.asJson(ImmutableMap.of(243          "using", "id",244          "value", "tasty"))));245    List<Map<String, Object>> elements = Values.get(res, new TypeToken<List<Map<String, Object>>>(){}.getType());246    assertThat(elements).hasSize(1);247    Object seenId = elements.get(0).get(Dialect.W3C.getEncodedElementKey());248    assertThat(seenId).isEqualTo(elementId);249  }250  private ArgumentMatcher<HttpRequest> matchesUri(String template) {251    UrlTemplate ut = new UrlTemplate(template);252    return req -> ut.match(req.getUri()) != null;253  }254}...Source:NodeFlags.java  
...76  public Set<String> driverNames = new HashSet<>();77  @Parameter(78    names = {"--driver-factory"},79    description = "Mapping of fully qualified class name to a browser configuration that this " +80                  "matches against. " +81                  "--driver-factory org.openqa.selenium.example.LynxDriverFactory " +82                  "'{\"browserName\": \"lynx\"}'",83    arity = 2,84    variableArity = true,85    splitter = NonSplittingSplitter.class)86  @ConfigValue(87    section = NODE_SECTION,88    name = "driver-factories",89    example = "[\"org.openqa.selenium.example.LynxDriverFactory '{\"browserName\": \"lynx\"}']")90  public List<String> driverFactory2Config;91  @Parameter(92    names = {"--grid-url"},93    description = "Public URL of the Grid as a whole (typically the address of the Hub " +94                  "or the Router)")...Source:CreateSessionTest.java  
...106    Map<String, Object> all = json.toType(107        new String(sessionResponse.getDownstreamEncodedResponse(), UTF_8),108        MAP_TYPE);109    // The status field is used by local ends to determine whether or not the session is a JWP one.110    assertThat(all.get("status")).matches(obj -> ((Number) obj).intValue() == ErrorCodes.SUCCESS);111    // The session id is a top level field112    assertThat(all.get("sessionId")).isInstanceOf(String.class);113    // And the value should contain the capabilities.114    assertThat(all.get("value")).isInstanceOf(Map.class);115  }116  @Test117  public void shouldPreferUsingTheW3CProtocol() throws URISyntaxException {118    String payload = json.toJson(ImmutableMap.of(119        "desiredCapabilities", ImmutableMap.of(120            "cheese", "brie"),121        "capabilities", ImmutableMap.of(122            "alwaysMatch", ImmutableMap.of("cheese", "brie"))));123    HttpRequest request = new HttpRequest(POST, "/session");124    request.setContent(utf8String(payload));...Source:LocalNodeFactory.java  
...92        toReturn.add(new DriverServiceSessionFactory(93          tracer,94          clientFactory,95          stereotype,96          capabilities -> slotMatcher.matches(stereotype, capabilities),97          driverServiceBuilder));98      });99    return toReturn.build();100  }101}...matches
Using AI Code Generation
1import org.openqa.selenium.grid.node.Node;2import org.openqa.selenium.grid.node.NodeId;3import org.openqa.selenium.grid.node.NodeStatus;4import org.openqa.selenium.remote.http.HttpClient;5import org.openqa.selenium.remote.http.HttpRequest;6import org.openqa.selenium.remote.http.HttpResponse;7import java.net.URI;8import java.net.URISyntaxException;9import java.util.function.Predicate;10public class NodeMatchesMethod {11    public static void main(String[] args) throws URISyntaxException {12        Predicate<HttpRequest> predicate = request -> request.getUri().getPath().contains("status");13        System.out.println(node.matches(predicate));14    }15}matches
Using AI Code Generation
1package com.selenium4beginners.java.basics;2import java.net.MalformedURLException;3import java.net.URL;4import java.util.concurrent.TimeUnit;5import org.openqa.selenium.By;6import org.openqa.selenium.WebDriver;7import org.openqa.selenium.WebElement;8import org.openqa.selenium.chrome.ChromeDriver;9import org.openqa.selenium.chrome.ChromeOptions;10import org.openqa.selenium.devtools.DevTools;11import org.openqa.selenium.devtools.v91.browser.Browser;12import org.openqa.selenium.devtools.v91.browser.model.BrowserContextID;13import org.openqa.selenium.devtools.v91.browser.model.WindowID;14import org.openqa.selenium.devtools.v91.emulation.Emulation;15import org.openqa.selenium.devtools.v91.page.Page;16import org.openqa.selenium.devtools.v91.page.model.FrameID;17public class DevToolsExample {18	public static void main(String[] args) throws MalformedURLException, InterruptedException {19		System.setProperty("webdriver.chrome.driver", "C:\\Users\\Your Name\\Downloads\\chromedriver_win32\\chromedriver.exe");20		ChromeOptions options = new ChromeOptions();21		options.addArguments("--incognito");22		options.addArguments("--start-maximized");23		WebDriver driver = new ChromeDriver(options);24		DevTools devTools = ((ChromeDriver) driver).getDevTools();25		devTools.createSession();26		devTools.send(Emulation.setDownloadBehavior()27				.withBehavior("allow")28				.withDownloadPath("C:\\Users\\Your Name\\Downloads"));29		devTools.send(Emulation.setTimezoneOverride()30				.withTimezoneId("Europe/London"));31		devTools.send(Emulation.setGeolocationOverride()32				.withLatitude(51.507351)33				.withLongitude(-0.127758)34				.withAccuracy(100));35		devTools.send(Browser.setWindowBounds()36				.withWindowId(WindowID.WINDOWID_1)37				.withBounds(0, 0, 1920, 1080));matches
Using AI Code Generation
1package com.selenium4beginners.java.seleniumgrid;2import java.net.MalformedURLException;3import java.net.URL;4import org.openqa.selenium.WebDriver;5import org.openqa.selenium.remote.DesiredCapabilities;6import org.openqa.selenium.remote.RemoteWebDriver;7public class NodeStatus {8	public static void main(String[] args) throws MalformedURLException {9		DesiredCapabilities caps = new DesiredCapabilities();10		caps.setBrowserName("chrome");11		caps.setPlatform(org.openqa.selenium.Platform.WINDOWS);12		WebDriver driver = new RemoteWebDriver(new URL(hubURL), caps);13		System.out.println(((RemoteWebDriver) driver).getSessionId());14		System.out.println(((RemoteWebDriver) driver).getCapabilities());15		System.out.println(((RemoteWebDriver) driver).getCommandExecutor());16		System.out.println(((RemoteWebDriver) driver).getCommandExecutor().getClass());17		System.out.println(((RemoteWebDriver) driver).getCommandExecutor().toString());18		System.out.println(((RemoteWebDriver) driver).getCommandExecutor().toString().contains("org.openqa.selenium.grid.node"));19		System.out.println(((RemoteWebDriver) driver).getCommandExecutor().toString().contains("org.openqa.selenium.remote.server.SeleniumServer"));20		System.out.println(((RemoteWebDriver) driver).getCommandExecutor().toString().contains("org.openqa.selenium.remote.server.DriverServlet"));21		driver.quit();22	}23}matches
Using AI Code Generation
1package org.openqa.selenium.grid.node;2import com.google.common.collect.ImmutableMap;3import com.google.common.collect.ImmutableSet;4import com.google.common.collect.ImmutableSortedSet;5import com.google.common.collect.Iterables;6import com.google.common.collect.Sets;7import com.google.common.collect.Streams;8import com.google.common.collect.TreeMultimap;9import com.google.common.collect.TreeTraverser;10import com.google.common.util.concurrent.ListenableFuture;11import com.google.common.util.concurrent.SettableFuture;12import com.google.common.util.concurrent.Uninterruptibles;13import org.openqa.selenium.Capabilities;14import org.openqa.selenium.ImmutableCapabilities;15import org.openqa.selenium.NoSuchSessionException;16import org.openqa.selenium.SessionNotCreatedException;17import org.openqa.selenium.events.EventBus;18import org.openqa.selenium.grid.data.Availability;19import org.openqa.selenium.grid.data.CreateSessionRequest;20import org.openqa.selenium.grid.data.NodeStatus;21import org.openqa.selenium.grid.data.Session;22import org.openqa.selenium.grid.data.SessionClosedEvent;23import org.openqa.selenium.grid.data.SessionCreatedEvent;24import org.openqa.selenium.grid.data.SessionId;25import org.openqa.selenium.grid.data.SessionInfo;26import org.openqa.selenium.grid.data.SessionRequest;27import org.openqa.selenium.grid.data.SessionRequestEvent;28import org.openqa.selenium.grid.data.SessionRequestListener;29import org.openqa.selenium.grid.data.SessionRequestTimedOutEvent;30import org.openqa.selenium.grid.data.SessionStartedEvent;31import org.openqa.selenium.grid.data.SessionTerminatedEvent;32import org.openqa.selenium.grid.data.SlotId;33import org.openqa.selenium.grid.data.Stoppable;34import org.openqa.selenium.grid.node.local.LocalNode;35import org.openqa.selenium.grid.security.Secret;36import org.openqa.selenium.grid.sessionmap.SessionMap;37import org.openqa.selenium.grid.web.Values;38import org.openqa.selenium.internal.Require;39import org.openqa.selenium.json.Json;40import org.openqa.selenium.json.JsonInput;41import org.openqa.selenium.json.JsonOutput;42import org.openqa.selenium.json.TypeToken;43import org.openqa.selenium.remote.http.HttpMethod;44import org.openqa.selenium.remote.http.HttpRequest;45import org.openqa.selenium.remote.http.HttpResponse;46import org.openqa.selenium.remote.tracing.Tracer;47import org.openqa.selenium.remote.tracing.Tracer.SpanBuilder;48import org.openqa.selenium.remote.tracing.Tracer.SpanBuilder.AttributeValue;49import org.openqa.selenium.remote.tracing.Tracer.SpanBuilder.AttributeValue.AttributeType;50import org.openqa.selenium.remote.tracing.Tracer.SpanBuilder.SpanKind;51importLambdaTest’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!!
