Selenium Grid Tutorial: Parallel Testing Information With Examples – DZone – Uplaza

Selenium Grid, a vital part of the Selenium suite, lets you run check circumstances concurrently in several browsers and browser variations.

Working assessments sequentially on a single machine is all the time time-consuming, as you’ll be able to solely load just a few browsers in your native machine, limiting testing capabilities (e.g., Home windows could not check Safari). That is the place the Selenium Grid setup permits testing on all main browsers, working programs, and cell units, making certain broad browser protection and a uniform person expertise.

What Is a Selenium Grid?

Selenium Grid helps in operating the Selenium assessments on distant machines. It makes use of a proxy server that’s run utilizing a Selenium server and permits for the upkeep of various browser configurations on the central degree. It allows the assessments to run in parallel on different browser variations, thus serving to carry out cross-browser testing. Furthermore, Selenium Grid permits parallel testing towards numerous browsers and OS combos via a client-server mannequin. Right here, the server is called the Hub, which has a number of purchasers with which to work together.

Why Use Selenium Grid?

Selenium Grid eases the assorted duties whereas performing automated testing. Right here is why you must use Selenium Grid setup to run your check suites:

  • Open supply and free: Selenium Grid is an open-source challenge. Groups can use it without cost. The documentation is up to date commonly with each launch, making issues like set up, configuration, and utilization simpler for the customers.
  • Permits cross-browser testing: A number of browsers are gaining recognition, and each particular person prefers to make use of the browser of his alternative for browning web sites. It turns into mandatory for companies to check their web sites on a number of browsers. Selenium Grid 4 allows the software program groups to carry out cross browser testing rapidly, permitting them to configure a number of browsers simply.
  • Helps a number of browser variations: One other essential characteristic is that Selenium Grid permits customers to configure a number of browser variations simply. This helps check web sites in several browsers and their variations, enabling groups to detect the problems and repair them on the earliest.
  • Helps parallel testing: This is without doubt one of the most essential options behind utilizing Selenium Grid for testing. It helps run the assessments in parallel, permitting the groups to avoid wasting time on check execution and get sooner outcomes and suggestions on the builds.

Options of Selenium Grid

The next are the salient options of Selenium Grid 4:

Structure Assist

Within the earlier model of Selenium Grid, solely two processes have been accessible, i.e., Hub and Nodes. The Selenium Grid 4 structure helps the next six processes, which permits for deployment in several methods:

  • Router
  • Distributor
  • Session Map
  • New Session Queue
  • Node
  • Occasion Bus

Completely different Grid Roles

Selenium Grid may be configured within the following 3 ways:

  • Standalone Mode
  • Classical Grid (Hub and Node)
  • Absolutely Distributed (Occasion Bus, New Session Queue, Session Map, Distributor, Router and Node)

Docker Assist

Selenium Grid gives out-of-the-box help for Docker. The Docker daemon runs on port 2375.

Observability

Observability in Selenium Grid permits understanding and debugging of inner working as it’s designed to be totally distributed. The next three are the primary pillars that assist in offering detailed insights into observability.

GraphQL Question Assist

GraphQL, a question language for APIs, can be utilized to question and fetch the info that the person requires. With Selenium Grid, GraphQL queries are supported. A easy question can fetch the main points of the session, node and grid, present session rely, max session rely, all session particulars, and so on.

Assist for Customizing a Node

With Selenium Grid, the Nodes may be personalized and up to date in accordance with the prerequisite for check execution. For instance, doing a little further setup earlier than the session begins execution, equally operating clean-up jobs post-session is full.

Assist for Exterior Information Retailer

Selenium Grid permits us to avoid wasting the data associated to the presently operating classes into an exterior information retailer that may very well be backed by our favourite database, or the Redis Cache system may also be used.

Notice: With Selenium 4 in place, Selenium Grid 3 has been deprecated, and the official Selenium documentation recommends utilizing the Selenium Grid 4. To be taught concerning the modifications between Selenium Grid 3 and Selenium 4, seek advice from Selenium 3 vs Selenium 4. 

Parts of Selenium Grid

The next are the six most important elements of Selenium Grid: Supply

  • Router: Acts because the gateway for the grid, receiving exterior requests and directing them to the proper element for dealing with.
  • Distributor: Manages the registration and capabilities of Nodes within the grid. It additionally assigns new session requests to the suitable Nodes from the Session Queue and updates the Grid’s mannequin with Node standing.
  • Session map: Shops the hyperlinks between Session IDs and Nodes, facilitating environment friendly request routing by the Router.
  • Session queue: Holds incoming session requests in a First In, First Out (FIFO) order. It contains settings for request timeouts and retry intervals, making certain organized and environment friendly processing of requests.
  • Node: Executes assessments inside a distributed community. To obtain acceptable check requests, Nodes with particular configurations should register with the Distributor.
  • Occasion bus: Facilitates inner communication between grid elements utilizing messages to keep away from direct HTTP calls. It’s activated when the grid begins in totally distributed mode.

Methods to Configure a Selenium Grid Setup

For Selenium Grid setup, listed here are some stipulations that you should comply with:

  1. Guarantee system set up of Java Runtime Surroundings (JRE) or Java Improvement Equipment (JDK). Want the newest JDK model; nonetheless, any model above Java 11 suffices (Java 11 is the minimal model supported by Selenium).
  2. Obtain Selenium Standalone server JAR recordsdata.
  3. Obtain the Java JAR recordsdata.

Now, let’s see the steps for Selenium Grid setup implementation:

Step 1: Configure a Standalone Grid 

Standalone Grid supplies a totally purposeful grid with a single command inside a single course of. It completely combines all of the grid elements and may run on a single machine.

 The next command may be run from the terminal to start out the Selenium Grid in Standalone Mode:

java -jar selenium-server-.jar standalone

Make sure you navigate to the folder the place you downloaded and extracted the Selenium JAR recordsdata. These recordsdata are positioned on My Laptop within the H:selenium_grid folder. 

After executing the command, navigate to http://localhost:4444 to test the totally purposeful Selenium Grid. It may be seen that Selenium Grid is totally purposeful with 4 cases of Chrome, Firefox, Edge, and IE browsers.

Step 2: Configure Hub and Nodes 

To begin the Hub, open a command immediate or terminal, navigate to the listing the place the Selenium Standalone Server JAR file is saved, and run the under command:

java -jar selenium-server-.jar hub

This command would launch a Selenium Grid hub on port 4444 by default. It may be verified by navigating to http://localhost:4444  Subsequent, we have to configure the Nodes to make it totally purposeful.

After the Hub is began, the Nodes should be set as much as run the browser session for check execution. The Nodes may be arrange in several machines. Nonetheless, it must be famous that these machines ought to have a JDK/JRE already put in. The Nodes may also be arrange on the identical machine Hub runs. 

To configure a Node, open a command immediate or terminal and navigate to the listing the place you saved the browser driver recordsdata. 

Step 3: Configure Chrome Browser within the Selenium Grid Setup 

The next command must be executed within the new occasion of the command immediate to start out a Node with the Chrome browser:

java -jar selenium-server-4.21.0.jar node --detect-drivers false --driver-configuration display-name="Chrome" max-sessions=1 stereotype="{"browserName":"chrome","platformName": "Home windows 11"}" --port 6161

The above command will begin a Node with Chrome browser with one session on port 6161. If we have to enhance the session, we are able to replace the worth for the max-sessions parameter within the above command. 

The Node may be verified on the Selenium Grid UI by navigating to http://localhost:4444. Let’s now add one other node with the Firefox browser to the grid.

Step 4: Configure Firefox Browser within the Selenium Grid Setup 

Open a brand new occasion of the command immediate or terminal and run the next command:

java -jar selenium-server-4.21.0.jar node --detect-drivers false --driver-configuration display-name="Firefox" max-sessions=2 stereotype="{"browserName":"firefox","platformName": "Home windows 11"}" --port 6162

The above command will spin a brand new Node with the 2 Firefox browser classes operating. Notice that we’ve began this Node on a unique port,i.e., 6162Let’s now add a 3rd Node with the Microsoft Edge browser.

Step 5: Configure Edge Browser within the Selenium Grid Setup 

Open a brand new occasion of the command immediate or terminal and run the next command:

java -jar selenium-server-4.21.0.jar node --detect-drivers false --driver-configuration display-name="Edge" max-sessions=3 stereotype="{"browserName":"MicrosoftEdge","platformName": "Home windows 11"}" --port 6163

The above command will configure three Edge browser classes in a brand new Node on port 6163

Let’s confirm the addition of a brand new Node by navigating and checking http://localhost:4444. 

Step 6: Configure a Distributed Grid 

Every element is launched independently in a Distributed Grid setup, ideally on separate machines. Comply with the next steps to configure the Distributed Grid:

1. Begin the Occasion Bus

Open a brand new terminal or command immediate and run the next command to start out the Occasion Bus. Occasion Bus helps in inner communication between totally different grid elements.

java -jar selenium-server-4.21.0.jar event-bus --publish-events tcp://localhost:4442 --subscribe-events tcp://localhost:4443 --port 5557

2. Begin the New Session Queue

Begin the New Session Queue by including the brand new session requests to a queue. The Distributor queries it. The next command must be run after opening a brand new command immediate:

java -jar selenium-server-4.21.0.jar sessionqueue --port 5559

3. Begin the Session Map

Begin the Session Map subsequent, which can work together with the Occasion Bus and map session IDs to the Node the place the session is operating. Open a brand new command immediate and run the next command:

java -jar selenium-server-4.21.0.jar classes --publish-events tcp://localhost:4442 --subscribe-events tcp://localhost:4443 --port 5556

4. Begin the Distributor

The following step is to start out the Distributor which queries the New Session Queue for checking new session requests. When discovering the matching capabilities, it assigns a Node to the New Session request. Open the command immediate and run the next command:

java -jar selenium-server-4.21.0.jar distributor --publish-events tcp://localhost:4442 --subscribe-events tcp://localhost:4443 --sessions http://localhost:5556 --sessionqueue http://localhost:5559 --port 5553 --bind-bus false

5. Begin the Router

The following step is to start out the Router, which can direct new session requests to the queue and route requests for lively classes to the Node dealing with that session. Open the command immediate and run the next command:

java -jar selenium-server-4.21.0.jar router --sessions http://localhost:5556 --distributor http://localhost:5553 --sessionqueue http://localhost:5559 --port 4444

6. Begin the Nodes

Begin the Node to launch the browser classes, which can ultimately assist run our automated assessments. The next command will add one Node with 4 Chrome, Firefox, and Edge browser classes. It would additionally spin one session of IE browser by default.

java -jar selenium-server-4.21.0.jar node --publish-events tcp://localhost:4442 --subscribe-events tcp://localhost:4443

Navigate to http://localhost:4444 and test the grid in totally purposeful mode. 

How To Carry out Parallel Testing With Selenium Grid

It’s time for parallel testing utilizing the Selenium Grid setup. The assessments will likely be run in parallel on Chrome, Firefox, and Edge browsers. 

Take a look at Situation

  1. Navigate to the LambdaTest eCommerce Playground web site.
  2. Seek for a product utilizing the search bar on the homepage.
  3. Test the web page title of the search outcome web page.

Take a look at Implementation

The BaseTest class is created to handle WebDriver cases for operating assessments on a Selenium Grid. This class is obtainable within the seleniumgriddemo bundle within the src/check folder.

public class BaseTest {

   non-public static remaining ThreadLocal DRIVER = new ThreadLocal();

   public RemoteWebDriver getDriver() {
       return DRIVER.get();
   }

   non-public void setDriver(RemoteWebDriver remoteWebDriver) {
       DRIVER.set(remoteWebDriver);
   }

   @Parameters("browser")
   @BeforeClass(alwaysRun = true)
   public void setup(String browser) {
       strive {
           if (browser.equalsIgnoreCase("chrome")) {
               ChromeOptions chromeOptions = new ChromeOptions();
               chromeOptions.setCapability("se:name", "Test on Grid - Chrome");
               setDriver(new RemoteWebDriver(new URL("http://localhost:4444"), chromeOptions));

           } else if (browser.equalsIgnoreCase("firefox")) {
               FirefoxOptions firefoxOptions = new FirefoxOptions();
               firefoxOptions.setCapability("se:name", "Test on Grid - Firefox");
               setDriver(new RemoteWebDriver(new URL("http://localhost:4444"), firefoxOptions));

           } else if (browser.equalsIgnoreCase("edge")) {
               EdgeOptions edgeOptions = new EdgeOptions();
               edgeOptions.setCapability("se:name", "Test on Grid - Edge");
               setDriver(new RemoteWebDriver(new URL("http://localhost:4444"), edgeOptions));
           } else {
               throw new Error("Browser configuration is not defined!!");
           }

       } catch (MalformedURLException e) {
           throw new Error("Error setting up browsers in Grid");
       }
       getDriver().handle()
           .timeouts()
           .implicitlyWait(Length.ofSeconds(20));
   }

   @AfterTest(alwaysRun = true)
   public void tearDown() {
       getDriver().stop();
   }
}

The ThreadLocal variable holds the RemoteWebDriver occasion. Utilizing ThreadLocal ensures that every thread will get its personal occasion of RemoteWebDriver that may assist in parallel execution of assessments seamlessly. 

The setup() technique will take the title of the browser as a parameter and accordingly configure the browser for executing the assessments. The title of the browser will likely be set on runtime utilizing testng.xml file, as we’re utilizing the @Parameters annotation of TestNG for setting the browser title.  The RemoteWebDriver occasion will likely be instantiated utilizing the Selenium Grid URL that runs on http://localhost:4444 and setting the capabilities of the respective browser choice class.

The aptitude se:title will present the check title as an alternative of the session ID within the grid UI. 

The getDriver() technique returns the RemoteWebDriver occasion related to the present thread. 

Equally, the setDriver() technique will assign the RemoteWebDriver occasion to the present thread. 

The tearDown() technique will name the stop() technique on the RemoteWebDriver occasion to shut the session. 

A brand new check class named LocalGridDemoTests was created to implement the check situation mentioned earlier. This class extends the BaseTest class to make use of the configurations to run the check simply.

public class LocalGridDemoTests extends BaseTest {

   @Take a look at
   public void testSearchProduct() {
       getDriver().get("https://ecommerce-playground.lambdatest.io/");
       WebElement searchBox = getDriver().findElement(By.title("search"));

       String searchText = "iPhone";
       searchBox.sendKeys(searchText);
       WebElement searchBtn = getDriver().findElement(By.cssSelector("button.type-text"));
       searchBtn.click on();

       String pageHeader = getDriver().findElement(By.tagName("h1"))
           .getText();

       assertEquals(pageHeader, "Search - " + searchText);
   }
}

The testSearchProduct() technique will navigate to the LambdaTest eCommerce playground web site, and the search field will likely be positioned on the house web page utilizing the Title locator in Selenium. 

Subsequent, the check iPhone will likely be typed within the search field subject, and the Search button will likely be clicked. The web page header of the search outcome web page will likely be asserted by getting its textual content utilizing the tagName locator h1

Lastly, the assertion will likely be carried out to test that the textual content of the web page header matches with the textual content that was used for looking the product. The phrase Search is added as a prefix earlier than the anticipated search textual content, as this textual content seems as static textual content on the web page after something is searched. 

Take a look at Execution

The next testng.xml file is created for check execution functions. This testng.xml will assist us execute the assessments in parallel.

As talked about, the browser names are handed utilizing the parameter tag within the testng.xml file. Notice that we are going to use the tag parallel to run the assessments in parallel and supply the worth as assessments

This may run each check block accessible within the testng.xml file in parallel. The next is the screenshot of Selenium Grid UI exhibiting the classes operating in parallel. 

The next screenshot exhibits that the assessments have been executed efficiently in parallel: 

Selenium Grid is without doubt one of the strong elements of Selenium for configuring an area infrastructure for cross-browser testing. Nonetheless, there are particular limitations, and we must be particular whereas choosing the browser/browser variations and platforms for testing. 

Other than what is about up within the grid, we have to configure a further node to cater to our necessities. This might show expensive as we’d be required to buy new machines with a particular working system, corresponding to macOS or a specific model of Home windows. 

That is the place cloud platforms corresponding to LambdaTest may be useful because it saves us from the trouble of sustaining your Selenium Grid setup, so we might give attention to writing higher automation code. 

Parallel Testing at Scale Utilizing LambdaTest

LambdaTest is an AI-powered check execution platform on the cloud that lets you check your web sites and internet purposes throughout 3000+ combos of browsers, browser variations, and working programs. It gives a web based Selenium Grid that will help you carry out automation testing in parallel. 

Let’s strive operating our similar check case on the LambdaTest cloud grid. The LambdaTest Automation Capabilities Generator can be utilized to configure the specified capabilities, which might save a whole lot of our time spent in Selenium Grid setup when executed manually.

Take a look at Implementation

With LambdaTest, we solely have to create a RemoteWebDriver session utilizing the Distant Server URL, add the LambdaTest Username, Entry Key, and the grid URL within the script together with the automation capabilities, after which we’re good to go. 

A brand new bundle named lambdatestgriddemoTests is created within the src/check folder. A brand new check class, LambdaTestGridDemoTestsmakes use of the identical testSearchProduct() technique. 

This check class is prolonged by the BaseTest class, which holds all of the configuration strategies for operating assessments on the LambdaTest cloud grid.

A brand new BaseTest class is created to deal with the configurations:

public class BaseTest {

   non-public static remaining ThreadLocal DRIVER = new ThreadLocal();

   public RemoteWebDriver getDriver() {
       return DRIVER.get();
   }

   non-public void setDriver(RemoteWebDriver remoteWebDriver) {
       DRIVER.set(remoteWebDriver);
   }

   @BeforeTest
   @Parameters({ "browser", "browserVersion", "platform" })
   public void setup(String browser, String browserVersion, String platform) {
       remaining String userName = System.getenv("LT_USERNAME") == null ? "LT_USERNAME" : System.getenv("LT_USERNAME");
       remaining String accessKey = System.getenv("LT_ACCESS_KEY") == null ? "LT_ACCESS_KEY" : System.getenv("LT_ACCESS_KEY");
       remaining String gridUrl = "@hub.lambdatest.com/wd/hub";

       if (browser.equalsIgnoreCase("chrome")) {
           strive {
               setDriver(new RemoteWebDriver(new URL("http://" + userName + ":" + accessKey + gridUrl), getChromeOptions(browserVersion, platform)));

           } catch (remaining MalformedURLException e) {
               throw new Error("Could not start the chrome browser on LambdaTest cloud grid");
           }
       } else if (browser.equalsIgnoreCase("firefox")) {
           strive {
               setDriver(new RemoteWebDriver(new URL("http://" + userName + ":" + accessKey + gridUrl), getFirefoxOptions(browserVersion, platform)));

           } catch (remaining MalformedURLException e) {
               throw new Error("Could not start the firefox browser on LambdaTest cloud grid");
           }
       } else if (browser.equalsIgnoreCase("edge")) {
           strive {
               setDriver(new RemoteWebDriver(new URL("http://" + userName + ":" + accessKey + gridUrl), getEdgeOptions(browserVersion, platform)));

           } catch (remaining MalformedURLException e) {
               throw new Error("Could not start the firefox browser on LambdaTest cloud grid");
           }
       } else {
           throw new Error("Browser configuration is not defined!");
       }

       getDriver().handle()
           .timeouts()
           .implicitlyWait(Length.ofSeconds(20));
   }

   non-public ChromeOptions getChromeOptions(String browserVersion, String platform) {
       var browserOptions = new ChromeOptions();
       browserOptions.setPlatformName(platform);
       browserOptions.setBrowserVersion(browserVersion);
       browserOptions.setCapability("LT:Options", getLtOptions());

       return browserOptions;
   }

   non-public FirefoxOptions getFirefoxOptions(String browserVersion, String platform) {
       var browserOptions = new FirefoxOptions();
       browserOptions.setPlatformName(platform);
       browserOptions.setBrowserVersion(browserVersion);
       browserOptions.setCapability("LT:Options", getLtOptions());

       return browserOptions;
   }

   non-public EdgeOptions getEdgeOptions(String browserVersion, String platform) {
       var browserOptions = new EdgeOptions();
       browserOptions.setPlatformName(platform);
       browserOptions.setBrowserVersion(browserVersion);
       browserOptions.setCapability("LT:Options", getLtOptions());

       return browserOptions;
   }

   non-public HashMap getLtOptions() {
       remaining var ltOptions = new HashMap();
       ltOptions.put("project", "ECommerce playground website");
       ltOptions.put("build", "LambdaTest Ecommerce Website tests");
       ltOptions.put("name", "Search for a product test");
       ltOptions.put("w3c", true);
       ltOptions.put("visual", true);
       ltOptions.put("plugin", "java-testNG");
       return ltOptions;
   }

   @AfterTest
   public void tearDown() {
       getDriver().stop();
   }
}

The RemoteWebDriver occasion is held by the ThreadLocal variable. It ensures that every thread will get its occasion of RemoteWebDriver, permitting thread security to carry out parallel execution of the assessments. 

The browser title, model, and platform title will likely be offered on run time via the testng.xml file, as @Parameter annotation from TestNG is used to set it. The LambdaTest Username and Entry Key will likely be fetched from the atmosphere variable. 

There are a number of if statements within the setup() technique that carries situations for beginning the browser utilizing a RemoteWebDriver occasion with the precise model on the platform. The strategies getChromeOptions(), getFirefoxOptions(), and getEdgeOptions() will set the capabilities for beginning the browser on the cloud. 

Equally, the ltOptions() technique will set all of the frequent capabilities required for operating the assessments on the LambdaTest cloud grid. 

Take a look at Execution

The next testng.xml file will permit us to run the automated assessments in parallel on totally different browser/platform combos.

The browser, browser model, and platform values are offered utilizing the testng.xml file. This makes issues simpler if we simply need to add extra browser/platform combos to run the cross-browser assessments. 

The next screenshot from IntelliJ IDE exhibits the profitable execution of the assessments:  The check execution particulars may be seen on the LambdaTest Internet Automation dashboard:

Conclusion

Selenium Grid setup, if executed manually, may very well be difficult. Selenium testing on a cloud-based grid helps us run assessments in parallel and check on a unique configuration; the identical may be carried out on LambdaTest with out investing time and sources to configure Selenium Grid. 

Strive it as soon as by operating your automated assessments on this on-line grid, and tell us your suggestions within the feedback.

Share This Article
Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Exit mobile version