Selenium Grid, an integral part of the Selenium suite, allows you to run check circumstances concurrently in numerous browsers and browser variations.
Operating checks 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 cellular gadgets, making certain broad browser protection and a uniform person expertise.
What Is a Selenium Grid?
Selenium Grid helps in operating the Selenium checks 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 permits the checks to run in parallel on different browser variations, thus serving to carry out cross-browser testing. Furthermore, Selenium Grid permits parallel testing in opposition to varied browsers and OS mixtures by a client-server mannequin. Right here, the server is named the Hub, which has a number of purchasers with which to work together.
Why Use Selenium Grid?
Selenium Grid eases the varied duties whereas performing automated testing. Right here is why it is best to use Selenium Grid setup to run your check suites:
- Open supply and free: Selenium Grid is an open-source mission. Groups can use it free of charge. The documentation is up to date recurrently with each launch, making issues like set up, configuration, and utilization simpler for the customers.
- Allows cross-browser testing: A number of browsers are gaining recognition, and each particular person prefers to make use of the browser of his selection for browning web sites. It turns into essential for companies to check their web sites on a number of browsers. Selenium Grid 4 permits 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 necessary characteristic is that Selenium Grid permits customers to configure a number of browser variations simply. This helps check web sites in numerous 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 necessary options behind utilizing Selenium Grid for testing. It helps run the checks in parallel, permitting the groups to save lots of 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 Help
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 numerous methods:
- Router
- Distributor
- Session Map
- New Session Queue
- Node
- Occasion Bus
Totally different Grid Roles
Selenium Grid will 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 Help
Selenium Grid presents 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 Help
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 small print of the session, node and grid, present session rely, max session rely, all session particulars, and so on.
Help for Customizing a Node
With Selenium Grid, the Nodes will be personalized and up to date in keeping with the prerequisite for check execution. For instance, doing a little extra setup earlier than the session begins execution, equally operating clean-up jobs post-session is full.
Help for Exterior Knowledge Retailer
Selenium Grid permits us to save lots of the knowledge associated to the at present operating periods into an exterior information retailer that could possibly 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 study in regards to the adjustments between Selenium Grid 3 and Selenium 4, check with Selenium 3 vs Selenium 4.
Parts of Selenium Grid
The next are the six important parts of Selenium Grid: Supply
- Router: Acts because the gateway for the grid, receiving exterior requests and directing them to the best 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 consists of settings for request timeouts and retry intervals, making certain organized and environment friendly processing of requests.
- Node: Executes checks 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 parts utilizing messages to keep away from direct HTTP calls. It’s activated when the grid begins in totally distributed mode.
How you can Configure a Selenium Grid Setup
For Selenium Grid setup, listed below are some conditions that it’s essential to observe:
- Guarantee system set up of Java Runtime Atmosphere (JRE) or Java Growth Equipment (JDK). Want the newest JDK model; nonetheless, any model above Java 11 suffices (Java 11 is the minimal model supported by Selenium).
- Obtain Selenium Standalone server JAR information.
- Obtain the Java JAR information.
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 parts and might run on a single machine.
The next command will be run from the terminal to begin 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 information. These information are situated on My Pc 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 start out 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 beneath 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 have to be set as much as run the browser session for check execution. The Nodes will be arrange in numerous machines. Nonetheless, it needs to 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 information.
Step 3: Configure Chrome Browser within the Selenium Grid Setup
The next command needs to be executed within the new occasion of the command immediate to begin 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 will 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 periods operating. Notice that we have now began this Node on a distinct port,i.e., 6162. Let’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 periods 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. Observe 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 begin the Occasion Bus. Occasion Bus helps in inner communication between completely different grid parts.
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 needs to 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 is able to 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 periods --publish-events tcp://localhost:4442 --subscribe-events tcp://localhost:4443 --port 5556
4. Begin the Distributor
The subsequent step is to begin 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 subsequent step is to begin the Router, which is able to direct new session requests to the queue and route requests for energetic periods 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 periods, which is able to finally assist run our automated checks. The next command will add one Node with 4 Chrome, Firefox, and Edge browser periods. It’ll 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 checks will likely be run in parallel on Chrome, Firefox, and Edge browsers.
Take a look at State of affairs
|
Take a look at Implementation
The BaseTest
class is created to handle WebDriver cases for operating checks on a Selenium Grid. This class is on the market within the seleniumgriddemo
package deal within the src/check folder.
public class BaseTest {
personal static ultimate ThreadLocal DRIVER = new ThreadLocal();
public RemoteWebDriver getDriver() {
return DRIVER.get();
}
personal void setDriver(RemoteWebDriver remoteWebDriver) {
DRIVER.set(remoteWebDriver);
}
@Parameters("browser")
@BeforeClass(alwaysRun = true)
public void setup(String browser) {
attempt {
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(Period.ofSeconds(20));
}
@AfterTest(alwaysRun = true)
public void tearDown() {
getDriver().give up();
}
}
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 checks seamlessly.
The setup()
methodology will take the identify of the browser as a parameter and accordingly configure the browser for executing the checks. The identify 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 identify. 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 possibility class.
The potential se:identify
will present the check identify as a substitute of the session ID within the grid UI.
The getDriver()
methodology returns the RemoteWebDriver
occasion related to the present thread.
Equally, the setDriver()
methodology will assign the RemoteWebDriver
occasion to the present thread.
The tearDown()
methodology will name the give up()
methodology on the RemoteWebDriver
occasion to shut the session.
A brand new check class named LocalGridDemoTests
was created to implement the check state of affairs 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.identify("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()
methodology will navigate to the LambdaTest eCommerce playground web site, and the search field will likely be situated on the house web page utilizing the Identify 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 end result 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 checks 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 checks in parallel and supply the worth as checks
.
This can run each check block accessible within the testng.xml file in parallel. The next is the screenshot of Selenium Grid UI displaying the periods operating in parallel.
The next screenshot reveals that the checks have been executed efficiently in parallel:
Selenium Grid is without doubt one of the strong parts of Selenium for configuring a neighborhood 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 ready up within the grid, we have to configure an extra node to cater to our necessities. This might show expensive as we might be required to buy new machines with a particular working system, corresponding to macOS or a selected model of Home windows.
That is the place cloud platforms corresponding to LambdaTest will 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 permits you to check your web sites and internet purposes throughout 3000+ mixtures of browsers, browser variations, and working programs. It presents a web based Selenium Grid that will help you carry out automation testing in parallel.
Let’s attempt operating our identical check case on the LambdaTest cloud grid. The LambdaTest Automation Capabilities Generator can be utilized to configure the specified capabilities, which might save quite a lot of our time spent in Selenium Grid setup when carried out 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 package deal named lambdatestgriddemoTests
is created within the src/check folder. A brand new check class, LambdaTestGridDemoTests
, makes use of the identical testSearchProduct()
methodology.
This check class is prolonged by the BaseTest
class, which holds all of the configuration strategies for operating checks on the LambdaTest cloud grid.
A brand new BaseTest
class is created to deal with the configurations:
public class BaseTest {
personal static ultimate ThreadLocal DRIVER = new ThreadLocal();
public RemoteWebDriver getDriver() {
return DRIVER.get();
}
personal void setDriver(RemoteWebDriver remoteWebDriver) {
DRIVER.set(remoteWebDriver);
}
@BeforeTest
@Parameters({ "browser", "browserVersion", "platform" })
public void setup(String browser, String browserVersion, String platform) {
ultimate String userName = System.getenv("LT_USERNAME") == null ? "LT_USERNAME" : System.getenv("LT_USERNAME");
ultimate String accessKey = System.getenv("LT_ACCESS_KEY") == null ? "LT_ACCESS_KEY" : System.getenv("LT_ACCESS_KEY");
ultimate String gridUrl = "@hub.lambdatest.com/wd/hub";
if (browser.equalsIgnoreCase("chrome")) {
attempt {
setDriver(new RemoteWebDriver(new URL("http://" + userName + ":" + accessKey + gridUrl), getChromeOptions(browserVersion, platform)));
} catch (ultimate MalformedURLException e) {
throw new Error("Could not start the chrome browser on LambdaTest cloud grid");
}
} else if (browser.equalsIgnoreCase("firefox")) {
attempt {
setDriver(new RemoteWebDriver(new URL("http://" + userName + ":" + accessKey + gridUrl), getFirefoxOptions(browserVersion, platform)));
} catch (ultimate MalformedURLException e) {
throw new Error("Could not start the firefox browser on LambdaTest cloud grid");
}
} else if (browser.equalsIgnoreCase("edge")) {
attempt {
setDriver(new RemoteWebDriver(new URL("http://" + userName + ":" + accessKey + gridUrl), getEdgeOptions(browserVersion, platform)));
} catch (ultimate 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(Period.ofSeconds(20));
}
personal ChromeOptions getChromeOptions(String browserVersion, String platform) {
var browserOptions = new ChromeOptions();
browserOptions.setPlatformName(platform);
browserOptions.setBrowserVersion(browserVersion);
browserOptions.setCapability("LT:Options", getLtOptions());
return browserOptions;
}
personal FirefoxOptions getFirefoxOptions(String browserVersion, String platform) {
var browserOptions = new FirefoxOptions();
browserOptions.setPlatformName(platform);
browserOptions.setBrowserVersion(browserVersion);
browserOptions.setCapability("LT:Options", getLtOptions());
return browserOptions;
}
personal EdgeOptions getEdgeOptions(String browserVersion, String platform) {
var browserOptions = new EdgeOptions();
browserOptions.setPlatformName(platform);
browserOptions.setBrowserVersion(browserVersion);
browserOptions.setCapability("LT:Options", getLtOptions());
return browserOptions;
}
personal HashMap getLtOptions() {
ultimate 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().give up();
}
}
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 checks.
The browser identify, model, and platform identify will likely be offered on run time by 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 setting variable.
There are a number of if statements within the setup()
methodology that carries situations for beginning the browser utilizing a RemoteWebDriver
occasion with the particular model on the platform. The strategies getChromeOptions()
, getFirefoxOptions()
, and getEdgeOptions()
will set the capabilities for beginning the browser on the cloud.
Equally, the ltOptions()
methodology will set all of the widespread capabilities required for operating the checks on the LambdaTest cloud grid.
Take a look at Execution
The next testng.xml file will enable us to run the automated checks in parallel on completely different browser/platform mixtures.
The browser, browser model, and platform values are offered utilizing the testng.xml file. This makes issues simpler if we simply wish to add extra browser/platform mixtures to run the cross-browser checks.
The next screenshot from IntelliJ IDE reveals the profitable execution of the checks: The check execution particulars will be considered on the LambdaTest Net Automation dashboard:
Conclusion
Selenium Grid setup, if carried out manually, could possibly be difficult. Selenium testing on a cloud-based grid helps us run checks in parallel and check on a distinct configuration; the identical will be carried out on LambdaTest with out investing time and sources to configure Selenium Grid.
Attempt it as soon as by operating your automated checks on this on-line grid, and tell us your suggestions within the feedback.