Vous êtes sur la page 1sur 44

What Is Selenium Grid 2?

When To Use
Grid?
Earlier we learnt selenium WebDriver/Selenium 2 tutorials with
practical examples and you can find all webdriver tutorials links
on THIS PAGE. Selenium Grid 2 may be new for most of you but you
must needs to learn It because If you wants to run your selenium
software tests In multiple browser versions and OS parallelthen
you need Selenium Grid 2. Let's try to understand what Is selenium
Grid and when to use It.
What Is Selenium Grid 2?
Selenium Grid Is another project of selenium. Selenium grid provide us
facility for distributed software test execution. Using selenium Grid, We
can execute our selenium WebDriver software tests In different
browsers, different browsers versions and different browser versions
running on different operating systems In parallel at the same time.
Basically selenium grid has one hub and multiple nodes. Each node
with same or different environments (As per your requirement) to
executed tests In parallel.
Bellow given Images shows example structure of selenium Grid. You
can see there Is single Hub machine connected to multiple nodes(with
different configuration) machine. You need node machine as per your
requirement.

When To Use Grid 2?

Main questions Is what are the benefits of selenium grid and why we
needs to use It. Mainly there are two reasons behind usage of selenium
grid In software testing Industry.
1.
To perform compatibility testing - You can run same test In
multiple environments so that It will be very easy for you to
perform compatibility testing using selenium grid.
2.
To reduce test execution time - As you know, we can run same
test In multiple machines at same time so It will reduce your test
execution time.
Using selenium grid, you can speedup software test execution process.
Supposing your 50 software automation test cases takes 5 hours to
complete execution In 1 machine then selenium grid with 5 nodes
configuration will take only 1 hour to execute 50 test cases. This Is the
main benefit of using selenium Grid.
NEXT POST will describe you how to configure selenium grid from
scratch to run selenium WebDriver software test cases.

Selenium Grid 2 Configuration - Setup


Hub To Run Selenium WebDriver Tests
We learnt what is Selenium Grid 2 and when to use it in PREVIOUS
POST. Selenium Grid is another project of selenium so you need
to configure selenium grid 2 from scratch to execute selenium
webdriver software test cases parallel in grid. Let's try to configure
selenium grid In single machine and then we will run selenium
webdriver tests In It.
As described In my previous post, We need to setup one hub and
multiple nodes (number of nodes depends on your requirement) to
execute selenium webdriver software test cases parallel on selenium
grid
nodes.

What Is Hub?
In selenium grid, Hub is a central point which receive software test
requests and send those software test requests to nodes for execution.
In our case of selenium webdriver, When we start executing software
test on selenium grid, Grid hub will receive and manage test requests

and then send them to registered node machine. We can configure


node on same machine or different machines too. We will learn more
about nodes in upcoming post.

Setting Up Selenium Grid 2 Hub


To execute selenium webdriver test cases parallel In selenium grid, We
need to set up selenium grid hub In your machine which will provide
available capabilities and configuration to webdriver tests.
Step 1 : Download Selenium Standalone Server jar
You can download selenium standalone server from THIS PAGE.
Current latest version of selenium standalone server is 2.52.0 so you
will get "selenium-server-standalone-2.52.0.jar" file. Put it in D: drive.
Note : If your selenium standalone server version is different than use
that version number in all bellow steps. Otherwise it will not work for
you.
Step 2 : Start Selenium Grid Hub
To start hub,
1.
Open command prompt
2.
Navigate to D: drive by typing command D: in command prompt.
3.
Type bellow given command syntax in command prompt and
press ENTER button.
java -jar selenium-server-standalone-2.52.0.jar -port 4444 -role hub

Command elements

selenium-server-standalone-2.52.0.jar -> Selenium standalone


server jar file version. Modify It as per your jar file version in above
command if it is not 2.52.0.

4444 -> Port used by hub to listen nodes.


Note : Please restart hub and if face any issue on any stage during test.
To restart grid 2 hub

Press CTRL+c keys of keyboard to shutdown node.

Run above command once again to register node with hub.

Verify whether grid hub is running fine


It will show you message -> "Selenium Grid hub is up and running." as
shown in bellow image.

Now
you
can
access
selenium
grid
console
using
URL : http://localhost:4444/grid/console. Open this URL in any
browser. It will show you page like bellow.

That means selenium grid hub is configured properly and ready to use.
We will learn how to configure nodes for seleniun grid 2 hub in NEXT
POST.

How To Configure Selenium Grid 2 Node


To Run WebDriver Test
As described In my EARLIER POST, Selenium grid 2 Is useful to
execute webdriver software tests on multiple nodes In parallel. So we
need to set up selenium grid 2 nodes for webdriver software test
execution. But before that, Your selenium grid hub should be
configured and in running mode as described in my PREVIOUS POST.

Now lets configure selenium grid 2 single node to execute webdriver


software automation tests in parallel in selenium grid.
Note : Here we are configuring selenium grid node on same
machine where selenium grid hub is running for your easy
understanding. Later on we will learn how to configure hub and nodes
on different machines and run software automation test on it.

What Is Node
Node is the point which accept test requests from hub and execute
them. We can configure node in such a way to execute tests in parallel
on different browsers at the same time. Also we can set max number of
browsers allowed to run test at a time, timeout etc. in upcoming posts.

Registering Selenium Grid 2 Node To Hub


We need to register selenium grid node to hub so that hub can
understand where to run software automation tests when receive
request for test execution. But before that please read bellow given
prerequisites.

Prerequisites :
Selenium grid hub should be In running mode as described In
previous post.
"chromedriver.exe" file should be located in D: drive. It will be
needed to run tests in google chrome browser. Read THIS POST to
know from where to download it if you do not have "chromedriver.exe"
file.
"IEDriverServer.exe" file should be located in D: drive. It will be
needed to run tests in Internet explorer browser.Read THIS POST to
know
from
where
to
download
it
if
you
do
not
have "IEDriverServer.exe" file.
Internet explorer browser's protected modes should be enabled
for all zones as described in THIS POST and browser zoom level should
be set to 100% as described in THIS POST.
Now follow the steps given bellow.

1.
Open another command prompt (Separate than hub command
prompt).
2.
Navigate to D: drive by typing command D: in command prompt.
3.
Type bellow given command syntax in command prompt and
press ENTER button.
java -jar selenium-server-standalone-2.52.0.jar -role node
-Dwebdriver.ie.driver="D:/IEDriverServer.exe"
-Dwebdriver.chrome.driver="D:/chromedriver.exe" -hub
http://localhost:4444/grid/register -port 5566

Command elements

selenium-server-standalone-2.52.0.jar -> Selenium standalone


server jar file. Modify It as per your jar file version in above command if
it is not 2.52.0.

5566 -> port number which will be used by node.

http://localhost:4444/grid/register : URL to register node where


hub is running. Our current configuration is running hub and nodes on
same machine so localhost in URL will work here.
Note : If node Is running on different machine than the hub
machine then you need to replace IP address of hub machine with
"localhost" in above URL.
-Dwebdriver.ie.driver="D:/IEDriverServer.exe" :
Set
path
of IEDriverServer.exe file for node to run test in internet explorer
browser.
-Dwebdriver.chrome.driver="D:/chromedriver.exe" : Set path
of chromedriver.exe file for node to run test in google chrome browser.
Note : Please restart hub and node if face any issue on any stage
during test. To restart grid 2 node
Press CTRL+c keys of keyboard to shutdown node.
Run above command once again to register node with hub.
We can also configure how many browsers you need on specific
node(Example : 2 Firefox, 3 chrome and 3 IE browsers) and max how
many allowed browsers to run on specific node. We will learn it in
upcoming posts.

Verify whether grid node is running fine


When you type above command In command prompt, It will show you
message like "The node is registered to the hub and ready to use" as
shown In bellow Image. That means you have configured node
properly.

Now If you access URL : http://localhost:4444/grid/console. It will


show you page like bellow.

You can see, there are different browsers like 1 IE, 5 Firefox and 5
chrome browsers which you can use to run your software automation

test. Now, Selenium grid is ready to use where hub and one node are
running on same machine.
Now supposing we have 1 test case and wants to execute it in parallel
in different 3 browsers. Can we do it using this configuration? Answer is
Yes.. View my NEXT POST to know how to do it using selenium grid 2.
How To Use Selenium Grid 2 To Run WebDriver Test Cases In Parallel

Main advantage of selenium grid is we can run webdriver software


test cases in parallel using selenium grid 2 environment to reduce
software test execution time as described in THIS POST. Also It helps
us to perform compatibility testing as it is supporting multiple browsers
too. Earlier we have configured selenium grid 2 hub in THIS POST and
selenium grid nodes in THIS POST in just single machine. Now lets try
to use this environment to execute webdriver software automation
test cases in parallel.
Prerequisite : Selenium grid hub and node should be running as
described in previous steps.
I have created simple software automation test to execute it parallel in
multiple browsers using selenium grid. It will launch three browsers
(Mozilla firefox, google chrome and IE) parallel and then execute
same software automation test inside each browser.
Note : Please remove internet explorer related code stuff from bellow
given script if face any related error as it is not very stable with
selenium grid.
Create bellow give test in your eclipse project under Grid package.
SeGridTest.java

package Grid;
import static org.testng.Assert.fail;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import
import
import
import
import
import

org.openqa.selenium.By;
org.openqa.selenium.Capabilities;
org.openqa.selenium.WebDriver;
org.openqa.selenium.remote.DesiredCapabilities;
org.openqa.selenium.remote.RemoteWebDriver;
org.openqa.selenium.support.ui.ExpectedConditions;

import
import
import
import
import

org.openqa.selenium.support.ui.WebDriverWait;
org.testng.annotations.AfterTest;
org.testng.annotations.BeforeTest;
org.testng.annotations.Parameters;
org.testng.annotations.Test;

public class SeGridTest {


WebDriver driver = null;
private StringBuffer verificationErrors = new StringBuffer();
// Pass plateform, browser and url parameters to launch browser and URL in
given plateform.
@Parameters({ "platform", "browser", "url" })
@BeforeTest(alwaysRun = true)
public void setup(String platform, String browser, String url) throws
MalformedURLException {
DesiredCapabilities caps = new DesiredCapabilities();
// Set Platforms based on parameter received from testng.xml.
caps.setPlatform(org.openqa.selenium.Platform.WINDOWS);
// Set browser capability based on parameter received from testng.xml.
if (browser.equalsIgnoreCase("Internet Explorer"))
caps = DesiredCapabilities.internetExplorer();
if (browser.equalsIgnoreCase("Firefox"))
caps = DesiredCapabilities.firefox();
if (browser.equalsIgnoreCase("chrome"))
caps = DesiredCapabilities.chrome();
// Open browser on grid node.

driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"),caps);


driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.manage().window().maximize();
// Open URL of Application
driver.get(url);
}
// Simple test method to execute.
@Test(description = "Wait for button enabled")
public void waitForButtonEnabled() throws InterruptedException {
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("#submitButt
on")));
driver.findElement(By.xpath("//input[@id='submitButton']")).click();
}
// Simple test method to execute.
@Test(description = "Wait for button enabled", dependsOnMethods =
{ "waitForButtonEnabled" })
public void testCalc() throws InterruptedException {
driver.navigate().to("http://only-testingblog.blogspot.in/2014/04/calc.html");
driver.findElement(By.xpath("//input[@id='2']")).click();
driver.findElement(By.xpath("//input[@id='plus']")).click();
driver.findElement(By.xpath("//input[@id='5']")).click();
driver.findElement(By.xpath("//input[@id='equals']")).click();
String result =
driver.findElement(By.xpath("//input[@id='Resultbox']")).getAttribute("value")
;
// Get Browser name and version.
Capabilities caps = ((RemoteWebDriver) driver).getCapabilities();
String browserName = caps.getBrowserName();
String browserVersion = caps.getVersion();
// Get OS name.
String os = System.getProperty("os.name").toLowerCase();
// Print test result with browser and OS version detail.
System.out.println("OS = " + os + ", Browser = " + browserName + " "+
browserVersion + " Test Result = " + result);
}

@AfterTest
public void afterTest() {
// Close the browser
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
}

If you remember, We have used parallel in testng.xml file to


execute software automation tests in parallel in selenium webdriver as
described in THIS POST. We will use same thing here but using
selenium grid.
You can see, We have used parameters (plateform, browser and url)
with setup method. All these parameters will be served from testnx.xml
file as bellow. We have configured three test in bellow given xml file
with different browser parameter to run test in different browsers.
Create bellow given testng.xml file under your project and run it.
testng.xml
<!--Set thread-count = 3 to execute test parallel in 3 max browsers at at
time. You can increase it-->
<suite name="Parallel Tests" verbose="1" thread-count="3" parallel="tests">
<tests>
<!--Set test parameters to execute test in IE browser on windows
plateform.-->
<test name="Windows+IE Test" >
<parameters>
<parameter name="platform" value="Windows" />
<parameter name="browser" value="Internet Explorer" />
<parameter name="url" value="http://only-testingblog.blogspot.in/2014/01/textbox.html" />
</parameters>
<classes>

<class name="Grid.SeGridTest" />


</classes>
</test>
<!--Set test parameters to execute test in Firefox browser on windows
plateform.-->
<test name="Windows+Firefox Test" >
<parameters>
<parameter name="platform" value="Windows" />
<parameter name="browser" value="Firefox" />
<parameter name="url" value="http://only-testingblog.blogspot.in/2014/01/textbox.html" />
</parameters>
<classes>
<class name="Grid.SeGridTest" />
</classes>
</test>
<!--Set test parameters to execute test in chrome browser on windows
plateform.-->
<test name="Windows+chrome Test" >
<parameters>
<parameter name="platform" value="Windows" />
<parameter name="browser" value="chrome" />
<parameter name="url" value="http://only-testingblog.blogspot.in/2014/01/textbox.html" />
</parameters>
<classes>
<class name="Grid.SeGridTest" />
</classes>
</test>
</tests>
</suite>

Now, execute above testng.xml file and observe test execution process.
It will launch three browsers parallel and then execute tests in all
three browsers. At the end of test execution, It will print result in
console as bellow.

OS = windows 7, Browser = chrome 43.0.2357.132 Test Result = 7


OS = windows 7, Browser = internet explorer 8 Test Result = 7
OS = windows 7, Browser = firefox 38.0.5 Test Result = 7

Testng result will looks like bellow.

This is the way to execute selenium webdriver software


automation test in parallel multiple browsers using selenium grid
2 to perform compatibility testing.

Selenium Grid 2 - Using @DataProvider


To Run Parallel WebDriver Tests
In my previous post, We learnt how to execute selenium
WebDriver single software automation test in multiple browsers in
parallel using Selenium Grid 2. We had used "parameter" tag in
testng.xml file to feed browser name in which your software
automation test needs to run in parallel. Instead of using @Parameters,
We can use @DataProvider annotation method to feed browser names
and run selenium WebDriver test in parallelusing selenium Grid 2.

If you use @Parameters, You need to write same test multiple


times(Depends on number of browsers) in testng.xml file. Main benefit
of using @DataProvider annotation method is you no need to write
same software automation test case name multiple times in testng.xml
file. You have to write it only once in testng.xml file. @DataProvider
annotation method will provide browser details to @Test method. To
run test in parallel, you need to set (parallel=true) with @DataProvider
annotation. Let's try it with simple example.
My requirement is : I wants to run my selenium software automation
test parallel in 3 browsers using selenium grid 2 and testng annotation
@DataProvider.
Prerequisites :

Selenium Grid 2 hub should be in running mode as described


in THIS POST.

Selenium Grid 2 node should be registered with hub and in


running mode as described in THIS POST.

Also IE browser's protected modes should be enabled for all


zones as described in THIS POST and zoom level should be set to 100%
as described in THIS POST if you are running your test in IE browser
too.
I am assuming your grid 2 hub and node are working fine and now this
is time to launch software automation test. Write bellow given test in
eclipse.
Note : Please remove internet explorer related code stuff from bellow
given script if face any related error as it is not very stable with
selenium grid.
fillingForm.java
package Grid2;
import
import
import
import

java.net.MalformedURLException;
java.net.URL;
java.util.concurrent.TimeUnit;
org.openqa.selenium.By;

import
import
import
import
import

org.openqa.selenium.Platform;
org.openqa.selenium.remote.DesiredCapabilities;
org.openqa.selenium.remote.RemoteWebDriver;
org.testng.annotations.DataProvider;
org.testng.annotations.Test;

public class fillingForm {


//Used dataProvider parameter to get data from @DataProvider annotation
method.
//Can accept object array data(browser name, First Name and Last Name) from
getNames method.
@Test(dataProvider = "getNames")
public void gmailLogin(String browser, String fName, String lName) throws
MalformedURLException, InterruptedException {
//Initialize DesiredCapabilities null.
DesiredCapabilities cap = null;
//Initialize browser driver as per data received from getNames().
if (browser.equals("firefox")) {
//Set firefox browser capabilities for windows platform.
cap = DesiredCapabilities.firefox();
cap.setBrowserName("firefox");
cap.setPlatform(Platform.WINDOWS);
} else if (browser.equals("chrome")) {
//Set chrome browser capabilities for windows platform.
cap = DesiredCapabilities.chrome();
cap.setBrowserName("chrome");
cap.setPlatform(Platform.WINDOWS);
} else if (browser.equals("iexplore")) {
//Set IE browser capabilities for windows platform.
cap = DesiredCapabilities.internetExplorer();
cap.setBrowserName("internet explorer");
cap.setPlatform(Platform.WINDOWS);
}
//Initialize RemoteWebDriver on grid 2 node with browser capability.
RemoteWebDriver driver = new RemoteWebDriver(new
URL("http://localhost:4444/wd/hub"), cap);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//Open URL in requested browsers of node and execute test steps.

driver.get("http://only-testing-blog.blogspot.in/2014/05/form.html");
driver.findElement(By.name("FirstName")).sendKeys(fName);
driver.findElement(By.name("LastName")).sendKeys(lName);
driver.quit();
}
//Created @DataProvider annotation method to supply data(browser name, First
Name and Last Name) for test
@DataProvider(parallel=true)
public Object[][] getNames(){
Object data[][] = new Object[3][3];
data[0][0] = "firefox";
data[0][1] = "FirstName1";
data[0][2] = "LastName1";
data[1][0] = "chrome";
data[1][1] = "FirstName2";
data[1][2] = "LastName2";
data[2][0] = "iexplore";
data[2][1] = "FirstName3";
data[2][2] = "LastName3";
return data;
}
}

You can see in above test. We have used @DataProvider annotation


method with (parallel=true) to supply data to @Test method. So no
need to set @Parameter in testng.xml file. Use bellow given testng.xml
file to run above test.
testng.xml
<suite name="My Test Suite" verbose="2" parallel="tests" thread-count="5">
<test name="Selenium Grid Test">
<classes>
<class name="Grid2.fillingForm" />
</classes>
</test>
</suite>

Execute above test and verify execution. It will run test in parallel in
different three browsers. This way you can use @DataProvider
annotation method with (parallel=true) at place of @Parameter to
execute test in different browser parallel using selenium grid 2.

Usage Of "maxInstances" In Grid 2 To


Set Allowed Max Number Of Browser
Instances
"maxInstances" is configuration parameter which is used
during selenium grid 2 node configuration. Using "maxInstances" in
selenium grid 2, We can set "how many max number of same
browser instances are allowed to open and run software test at same
time". "maxInstances" tells node machine to not allow more than
allowed instances on that specific machine at the same time. Lets
discuss one example to cleat your doubts.
If you launch selenium grid 2 node with default configuration as
described in THIS POST, It will set 1 IE, 5 Firefox and 5 chrome
browsers instances on node machine as bellow.

With this config, you can run your software automation tests in parallel
on 1 IE browser, 5 Firefox browsers and 5 chrome browser at a time.
That means node is not capable to run your tests in 2 IE browsers or 6
Firefox browsers or 6 chrome browsers at a time. Let's see it practically
to verify how it works if not set required browser instances on node.
Example Scenario: I have two software automation test cases as
bellow and i wants to execute both of them in parallel on 2 IE, 2 Google
chrome and 2 Firefox browsers at the same time. Means it should open
6 browser at a time on node machine to execute both software
automation test cases in all three browsers concurrently. Supposing i
am using default node configuration (1 IE, 5 Chrome and 5 Firefox
instances at a time) to run above scenario. It will start executing test in
all 6 browser instances at the same time? No.. First it will launch 5
browser instances(1 IE, 2 Google chrome and 2 Firefox) only and
execute test on them. Remaining 1 IE browser instance will be launched
and executes test once previous IE instance completes test execution
and getting closed. That means your test will not run on 2 IE browser
instances at the same time using this node configuration.
Launch selenium grid hub as described in THIS POST and selenium grid
node as described in THIS POST and then execute bellow given tests.
Note : Please remove internet explorer related code stuff from bellow
given script if face any related error as it is not very stable with
selenium grid.
fillingForm.java
package Grid2;
import
import
import
import
import
import

java.net.MalformedURLException;
java.net.URL;
java.util.concurrent.TimeUnit;
org.openqa.selenium.By;
org.openqa.selenium.Platform;
org.openqa.selenium.remote.DesiredCapabilities;

import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class fillingForm {
// Used dataProvider parameter to get data from @DataProvider annotation
method.
// Can accept object array data(browser name, First Name and Last Name) from
getNames method.
@Test(dataProvider = "getNames")
public void gmailLogin(String browser, String fName, String lName) throws
MalformedURLException, InterruptedException {
System.out.println(browser);
// Initialize DesiredCapabilities null.
DesiredCapabilities cap = null;
// Initialize browser driver as per data received from getNames().
if (browser.equals("firefox")) {
// Set firefox browser capabilities for windows platform.
cap = DesiredCapabilities.firefox();
cap.setBrowserName("firefox");
cap.setPlatform(Platform.WINDOWS);
} else if (browser.equals("chrome")) {
// Set chrome browser capabilities for windows platform.
cap = DesiredCapabilities.chrome();
cap.setBrowserName("chrome");
cap.setPlatform(Platform.WINDOWS);
} else if (browser.equals("iexplore")) {
// Set IE browser capabilities for windows platform.
cap = DesiredCapabilities.internetExplorer();
cap.setBrowserName("internet explorer");
cap.setPlatform(Platform.WINDOWS);
}
// Initialize RemoteWebDriver on grid 2 node with browser capability.
RemoteWebDriver driver = new RemoteWebDriver(new
URL("http://localhost:4444/wd/hub"), cap);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

// Pause test for 20 minutes to check exactly how many concurrent browsers
opening at same time.
Thread.sleep(20000);
// Open URL in requested browsers of node and execute test steps.
driver.get("http://only-testing-blog.blogspot.in/2014/05/form.html");
driver.findElement(By.name("FirstName")).sendKeys(fName);
driver.findElement(By.name("LastName")).sendKeys(lName);
// Close browser instance.
driver.quit();
}
// Created @DataProvider annotation method to supply data(browser name, First
Name and Last Name) for test
@DataProvider(parallel = true)
public Object[][] getNames() {
Object data[][] = new Object[3][3];
data[0][0] = "firefox";
data[0][1] = "FirstName1";
data[0][2] = "LastName1";
data[1][0] = "chrome";
data[1][1] = "FirstName2";
data[1][2] = "LastName2";
data[2][0] = "iexplore";
data[2][1] = "FirstName3";
data[2][2] = "LastName3";
return data;
}
}

Calc.java
package Grid2;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;

import
import
import
import
import
import
import

org.openqa.selenium.By;
org.openqa.selenium.Platform;
org.openqa.selenium.remote.DesiredCapabilities;
org.openqa.selenium.remote.RemoteWebDriver;
org.testng.Assert;
org.testng.annotations.DataProvider;
org.testng.annotations.Test;

public class Calc {


// Used dataProvider parameter to get data from @DataProvider annotation
method.
// Can accept object array data(browser name, num1, num2 and expected sum
value) from getNames method.
@Test(dataProvider = "getCalcData")
public static void calcTest(String browser, String num1, String num2, String
expSumNum) throws MalformedURLException, InterruptedException {
System.out.println(browser);
// Initialize DesiredCapabilities null.
DesiredCapabilities cap = null;
// Initialize browser driver as per data received from getCalcData().
if (browser.equals("firefox")) {
// Set firefox browser capabilities for windows platform.
cap = DesiredCapabilities.firefox();
cap.setBrowserName("firefox");
cap.setPlatform(Platform.WINDOWS);
} else if (browser.equals("chrome")) {
// Set chrome browser capabilities for windows platform.
cap = DesiredCapabilities.chrome();
cap.setBrowserName("chrome");
cap.setPlatform(Platform.WINDOWS);
} else if (browser.equals("iexplore")) {
// Set IE browser capabilities for windows platform.
cap = DesiredCapabilities.internetExplorer();
cap.setBrowserName("internet explorer");
cap.setPlatform(Platform.WINDOWS);
}
// Initialize RemoteWebDriver on grid 2 node with browser capability.

RemoteWebDriver driver = new RemoteWebDriver(new


URL("http://localhost:4444/wd/hub"), cap);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// Pause test for 20 minutes to check exactly how many concurrent browsers
opening at same time.
Thread.sleep(20000);
driver.get("http://only-testing-blog.blogspot.in/2014/04/calc.html");
driver.findElement(By.xpath("//input[@id='Resultbox']")).clear();
driver.findElement(By.xpath("//input[@id='" + num1 + "']")).click();
driver.findElement(By.xpath("//input[@id='plus']")).click();
driver.findElement(By.xpath("//input[@id='" + num2 + "']")).click();
driver.findElement(By.xpath("//input[@id='equals']")).click();
// Get actual result and compare with expected result.
String strResult =
driver.findElement(By.xpath("//input[@id='Resultbox']")).getAttribute("value")
;
int actualResult = Integer.parseInt(strResult);
int expectedResult = Integer.parseInt(expSumNum);
Assert.assertEquals(actualResult, expectedResult);
// Close browser instance.
driver.quit();
}
// Created @DataProvider annotation method to supply data(browser name, num1,
num2 and expected sum value) for test
@DataProvider(parallel = true)
public Object[][] getCalcData() {
Object data[][] = new Object[3][4];
data[0][0] = "firefox";
data[0][1] = "1";
data[0][2] = "3";
data[0][3] = "4";
data[1][0]
data[1][1]
data[1][2]
data[1][3]

=
=
=
=

"chrome";
"2";
"5";
"7";

data[2][0]
data[2][1]
data[2][2]
data[2][3]

=
=
=
=

"iexplore";
"3";
"5";
"8";

return data;
}
}

testng.xml
<suite name="My Test Suite" verbose="2" parallel="classes" thread-count="15">
<test name="Selenium Grid Test">
<classes>
<class name="Grid2.fillingForm" />
<class name="Grid2.Calc" />
</classes>
</test>
</suite>

Create above given 2 software automation tests in eclipse and observe


its execution with above testng.xml file. It can launch 1 IE browser at a
time but i wants to execute my both tests on 2 IE browsers
concurrently.
To launch your above 2 software automation tests on 6 concurrent
browser at same time, you need to restart your node with bellow given
command where i have set maxInstances=2 for all three browser
instances.

Close current node using CTRL+c key press

Run bellow given command to register node with hub


with maxInstances=2 for all three browser instances.
java -jar selenium-server-standalone-2.52.0.jar -role node
-Dwebdriver.ie.driver="D:/IEDriverServer.exe"
-Dwebdriver.chrome.driver="D:/chromedriver.exe" -hub
http://localhost:4444/grid/register -port 5566 -browser
browserName=firefox,maxInstances=2 -browser browserName=chrome,maxInstances=2
-browser browserName=iexplore,maxInstances=2

maxInstances=2 : It will tell node to prepare 2 browsers


instances for that specific browser.
Now access URL = http://localhost:4444/grid/console in browser. It
will looks like bellow.

Rerun your testng.xml file using above node configuration. It will


launch 6 browsers (2 FF, 2 Chrome and 2 IE) at a time and run both
tests on all of them concurrently.
Note : You can set any value for maxInstances fro any browser.
Example : -browser browserName=firefox,maxInstances=25 will tell
node to set 25 firefox browser instances.
This way you can control max number of allowed browser instances of
same browser using maxInstances configuration parameter of grid 2.

Usage of "maxSession" In Grid 2 To Set


Number Of Max Session Of Browser
Instances
We learnt about "maxInstances" in my PREVIOUS POST. "maxSession"
is another configuration parameter which helps to set max allowed
sessions to run at a time on that specific node. Here session means

number of concurrent browsers in terms of all browser. It will not allow


that specific node to open browser more than value of "maxSession".
Let's understand with very simple example scenario.
Example scenario : Let's consider simple example. I wants to run 2
software automation test cases and both should run on 2 different
browsers concurrently(Firefox and Google chrome) using selenium
Grid. But my another condition is, Node should open max 2 browser at
a time. In this case, only "maxInstances" will not works for me but i
need to use maxSession" in node configuration. In this case i can set
maxSession = 2 for node to restrict only 2 browsers at a time. Let's
understand how it works with practical example.
Create bellow given software automation test cases in eclipse with
given testng.xml file.
Note : Please remove Internet explorer related code stuff from bellow
given script if face any related error as it is not very stable with
selenium grid.
fillingForm.java
package Grid2;
import
import
import
import
import
import
import
import
import

java.net.MalformedURLException;
java.net.URL;
java.util.concurrent.TimeUnit;
org.openqa.selenium.By;
org.openqa.selenium.Platform;
org.openqa.selenium.remote.DesiredCapabilities;
org.openqa.selenium.remote.RemoteWebDriver;
org.testng.annotations.DataProvider;
org.testng.annotations.Test;

public class fillingForm {


// Used dataProvider parameter to get data from @DataProvider annotation
method.
// Can accept object array data(browser name, First Name and Last Name) from
getNames method.
@Test(dataProvider = "getNames")

public void gmailLogin(String browser, String fName, String lName) throws


MalformedURLException, InterruptedException {
System.out.println(browser);
// Initialize DesiredCapabilities null.
DesiredCapabilities cap = null;
// Initialize browser driver as per data received from getNames().
if (browser.equals("firefox")) {
// Set firefox browser capabilities for windows platform.
cap = DesiredCapabilities.firefox();
cap.setBrowserName("firefox");
cap.setPlatform(Platform.WINDOWS);
} else if (browser.equals("chrome")) {
// Set chrome browser capabilities for windows platform.
cap = DesiredCapabilities.chrome();
cap.setBrowserName("chrome");
cap.setPlatform(Platform.WINDOWS);
} /*else if (browser.equals("iexplore")) {
// Set IE browser capabilities for windows platform.
cap = DesiredCapabilities.internetExplorer();
cap.setBrowserName("internet explorer");
cap.setPlatform(Platform.ANY);
cap.setVersion("8");
}*/
// Initialize RemoteWebDriver on grid 2 node with browser capability.
RemoteWebDriver driver = new RemoteWebDriver(new
URL("http://localhost:4444/wd/hub"), cap);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// Pause test for 20 minutes to check exactly how many concurrent browsers
opening at same time.
Thread.sleep(20000);
// Open URL in requested browsers of node and execute test steps.
driver.get("http://only-testing-blog.blogspot.in/2014/05/form.html");
driver.findElement(By.name("FirstName")).sendKeys(fName);
driver.findElement(By.name("LastName")).sendKeys(lName);
// Close browser instance.
driver.quit();

}
// Created @DataProvider annotation method to supply data(browser name, First
Name and Last Name) for test
@DataProvider(parallel = true)
public Object[][] getNames() {
Object data[][] = new Object[2][3];
data[0][0] = "firefox";
data[0][1] = "FirstName1";
data[0][2] = "LastName1";
data[1][0] = "chrome";
data[1][1] = "FirstName2";
data[1][2] = "LastName2";
/*
data[2][0] = "iexplore";
data[2][1] = "FirstName3";
data[2][2] = "LastName3";
*/
return data;
}
}

Calc.java
package Grid2;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import
import
import
import
import
import
import

org.openqa.selenium.By;
org.openqa.selenium.Platform;
org.openqa.selenium.remote.DesiredCapabilities;
org.openqa.selenium.remote.RemoteWebDriver;
org.testng.Assert;
org.testng.annotations.DataProvider;
org.testng.annotations.Test;

public class Calc {

// Used dataProvider parameter to get data from @DataProvider annotation


method.
// Can accept object array data(browser name, num1, num2 and expected sum
value) from getNames method.
@Test(dataProvider = "getCalcData")
public static void calcTest(String browser, String num1, String num2, String
expSumNum) throws MalformedURLException, InterruptedException {
System.out.println(browser);
// Initialize DesiredCapabilities null.
DesiredCapabilities cap = null;
// Initialize browser driver as per data received from getCalcData().
if (browser.equals("firefox")) {
// Set firefox browser capabilities for windows platform.
cap = DesiredCapabilities.firefox();
cap.setBrowserName("firefox");
cap.setPlatform(Platform.WINDOWS);
} else if (browser.equals("chrome")) {
// Set chrome browser capabilities for windows platform.
cap = DesiredCapabilities.chrome();
cap.setBrowserName("chrome");
cap.setPlatform(Platform.WINDOWS);
} /*else if (browser.equals("iexplore")) {
// Set IE browser capabilities for windows platform.
cap = DesiredCapabilities.internetExplorer();
cap.setBrowserName("iexplore");
cap.setPlatform(Platform.ANY);
cap.setVersion("8");
}*/
// Initialize RemoteWebDriver on grid 2 node with browser capability.
RemoteWebDriver driver = new RemoteWebDriver(new
URL("http://localhost:4444/wd/hub"), cap);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// Pause test for 20 minutes to check exactly how many concurrent browsers
opening at same time.
Thread.sleep(20000);
driver.get("http://only-testing-blog.blogspot.in/2014/04/calc.html");

driver.findElement(By.xpath("//input[@id='Resultbox']")).clear();
driver.findElement(By.xpath("//input[@id='" + num1 + "']")).click();
driver.findElement(By.xpath("//input[@id='plus']")).click();
driver.findElement(By.xpath("//input[@id='" + num2 + "']")).click();
driver.findElement(By.xpath("//input[@id='equals']")).click();
// Get actual result and compare with expected result.
String strResult =
driver.findElement(By.xpath("//input[@id='Resultbox']")).getAttribute("value")
;
int actualResult = Integer.parseInt(strResult);
int expectedResult = Integer.parseInt(expSumNum);
Assert.assertEquals(actualResult, expectedResult);
// Close browser instance.
driver.quit();
}
// Created @DataProvider annotation method to supply data(browser name, num1,
num2 and expected sum value) for test
@DataProvider(parallel = true)
public Object[][] getCalcData() {
Object data[][] = new Object[2][4];
data[0][0] = "firefox";
data[0][1] = "1";
data[0][2] = "3";
data[0][3] = "4";
data[1][0]
data[1][1]
data[1][2]
data[1][3]

=
=
=
=

"chrome";
"2";
"5";
"7";

=
=
=
=

"iexplore";
"3";
"5";
"8";

/*
data[2][0]
data[2][1]
data[2][2]
data[2][3]
*/
return data;
}
}

testng.xml
<suite name="My Test Suite" verbose="2" parallel="classes" thread-count="6">
<test name="Selenium Grid Test">
<classes>
<class name="Grid2.fillingForm" />
<class name="Grid2.Calc" />
</classes>
</test>
</suite>

without
using
"maxInstances"
First of all let's run our software automation test without using
"maxInstances" and then we will use "maxInstances" in node
configuration to check how it works.

Start grid 2 hub. You can view THIS POST to know how to start
hub.

Open command prompt and navigate to D: drive in command


prompt where selenium server jar file, IEDriver server file and
chromedriver file is stored.

Start grid 2 node using bellow given command. You can view THIS
POST to know prerequisite to start grid 2 node.
java -jar selenium-server-standalone-2.52.0.jar -role node
-Dwebdriver.ie.driver="D:/IEDriverServer.exe"
-Dwebdriver.chrome.driver="D:/chromedriver.exe" -hub
http://localhost:4444/grid/register -port 5566 -browser
browserName=firefox,maxInstances=2 -browser browserName=chrome,maxInstances=2
-browser browserName=iexplore,maxInstances=2

using "maxInstances"
Now execute above given 2 software automation test cases using
testng.xml file and observe test execution sequence. It will open 4
browsers at the same time and execute both test cases parallel in all 4
browsers.

Close current running node using CTRL+c keys.

Start node using bellow given command. Now we have used maxSession 2 in bellow given command to limit max any 2 browser
instances at a time.
java -jar selenium-server-standalone-2.52.0.jar -role node
-Dwebdriver.ie.driver="D:/IEDriverServer.exe"
-Dwebdriver.chrome.driver="D:/chromedriver.exe" -hub
http://localhost:4444/grid/register -port 5566 -browser
browserName=firefox,maxInstances=2 -browser browserName=chrome,maxInstances=2
-browser browserName=iexplore,maxInstances=2 -maxSession 2

Now run testng.xml file to execute above given 2 software


automation test cases and observe test execution sequence. It will
open only 2 browsers at a time and 2 requests will wait for slot to be
free as shown in bellow given image. You can see it by refreshing
console page when your tests start execution.

Once previous 2 requests will complete execution and close browser


instance, Remaining 2 requests will be executed by opening new 2
browser instances. Means you will see max 2 browser instances at a
time on your grid node machine to execute tests.
This way, maxSession will set max allowed browsers at a time to
execute test on grid node.

Set Selenium Grid Node "timeout"


When Running WebDriver Test

"timeout" is node configuration parameter using which you can set


timeout for selenium grid node browser session. If you set "timeout 20000" and run test, If node browser not receiving any
command and stay ideal for 20 seconds then it will be closed
automatically by -timeout parameter. That means it tells node
browser -> "wait max 20 seconds to receive any command else close
browser and clear session". Lets take practical example to
understand "timeout" clearly.
Earlier we learnt usage of "maxInstances" in THIS POST and
"maxSession" in THIS POST to configure selenium grid node so i hope
you are well aware about usage of both these parameters as we are
going to use them in this example too. Now let's create two selenium
software automation test cases as bellow and then try to run them
without timeout and then with timeout parameter.
fillingForm.java
package Grid2;
import
import
import
import
import
import
import
import
import

java.net.MalformedURLException;
java.net.URL;
java.util.concurrent.TimeUnit;
org.openqa.selenium.By;
org.openqa.selenium.Platform;
org.openqa.selenium.remote.DesiredCapabilities;
org.openqa.selenium.remote.RemoteWebDriver;
org.testng.annotations.DataProvider;
org.testng.annotations.Test;

public class fillingForm {


@Test(dataProvider = "getNames")
public void gmailLogin(String browser, String fName, String lName) throws
MalformedURLException, InterruptedException {
System.out.println(browser);
DesiredCapabilities cap = null;
if (browser.equals("firefox")) {

cap = DesiredCapabilities.firefox();
cap.setBrowserName("firefox");
cap.setPlatform(Platform.WINDOWS);
} else if (browser.equals("chrome")) {
cap = DesiredCapabilities.chrome();
cap.setBrowserName("chrome");
cap.setPlatform(Platform.WINDOWS);
}
RemoteWebDriver driver = new RemoteWebDriver(new
URL("http://localhost:4444/wd/hub"), cap);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/05/form.html");
driver.findElement(By.name("FirstName")).sendKeys(fName);
driver.findElement(By.name("LastName")).sendKeys(lName);
// Commented driver.quit(); to verify browser is being closed automatically
by timeout or not.
// driver.quit();
}
@DataProvider(parallel = true)
public Object[][] getNames() {
Object data[][] = new Object[2][3];
data[0][0] = "firefox";
data[0][1] = "FirstName1";
data[0][2] = "LastName1";
data[1][0] = "chrome";
data[1][1] = "FirstName2";
data[1][2] = "LastName2";
return data;
}
}

Calc.java
package Grid2;

import
import
import
import
import
import
import
import
import
import

java.net.MalformedURLException;
java.net.URL;
java.util.concurrent.TimeUnit;
org.openqa.selenium.By;
org.openqa.selenium.Platform;
org.openqa.selenium.remote.DesiredCapabilities;
org.openqa.selenium.remote.RemoteWebDriver;
org.testng.Assert;
org.testng.annotations.DataProvider;
org.testng.annotations.Test;

public class Calc {


@Test(dataProvider = "getCalcData")
public static void calcTest(String browser, String num1, String num2, String
expSumNum) throws MalformedURLException, InterruptedException {
System.out.println(browser);
DesiredCapabilities cap = null;
if (browser.equals("firefox")) {
cap = DesiredCapabilities.firefox();
cap.setBrowserName("firefox");
cap.setPlatform(Platform.WINDOWS);
} else if (browser.equals("chrome")) {
cap = DesiredCapabilities.chrome();
cap.setBrowserName("chrome");
cap.setPlatform(Platform.WINDOWS);
}
RemoteWebDriver driver = new RemoteWebDriver(new
URL("http://localhost:4444/wd/hub"), cap);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/04/calc.html");
driver.findElement(By.xpath("//input[@id='Resultbox']")).clear();
driver.findElement(By.xpath("//input[@id='" + num1 + "']")).click();
driver.findElement(By.xpath("//input[@id='plus']")).click();
driver.findElement(By.xpath("//input[@id='" + num2 + "']")).click();
driver.findElement(By.xpath("//input[@id='equals']")).click();

String strResult =
driver.findElement(By.xpath("//input[@id='Resultbox']")).getAttribute("value")
;
int actualResult = Integer.parseInt(strResult);
int expectedResult = Integer.parseInt(expSumNum);
Assert.assertEquals(actualResult, expectedResult);
// Commented driver.quit(); to verify browser is being closed automatically
by timeout or not.
// driver.quit();
}
@DataProvider(parallel = true)
public Object[][] getCalcData() {
Object data[][] = new Object[2][4];
data[0][0] = "firefox";
data[0][1] = "1";
data[0][2] = "3";
data[0][3] = "4";
data[1][0]
data[1][1]
data[1][2]
data[1][3]

=
=
=
=

"chrome";
"2";
"5";
"7";

return data;
}
}

testng.xml
<suite name="My Test Suite" verbose="2" parallel="classes" thread-count="6">
<test name="Selenium Grid Test">
<classes>
<class name="Grid2.fillingForm" />
<class name="Grid2.Calc" />
</classes>
</test>
</suite>

Test Configuration

2 Software Automation Test cases : fillingForm.java and Calc.java

driver.quit(); is commented from both software automation test


cases so webdriver will not close driver instance.

Both tests are configured to run in parallel using selenium grid 2.

Our aim is to run both software automation test cases in parallel


in 2 browsers and also it should run max 2 browsers at a time so we
will launch node with -maxSession 2.
Running test without timeout for node
First of all we will launch node without timeout parameter and execute
above test on it to check node browser status on completion of test.

Start grid hub as described in THIS POST.

Open command prompt and navigate to D: drive in command


prompt where selenium server jar file, IEDriver server file and
chromedriver file is stored.

Start grid node with -maxSession 2 to restrict 2 max browsers only


at a time. timeout is not used. Launch node using bellow given
command.
java -jar selenium-server-standalone-2.52.0.jar -role node
-Dwebdriver.ie.driver="D:/IEDriverServer.exe"
-Dwebdriver.chrome.driver="D:/chromedriver.exe" -hub
http://localhost:4444/grid/register -port 5566 -browser
browserName=firefox,maxInstances=2 -browser browserName=chrome,maxInstances=2
-browser browserName=iexplore,maxInstances=2 -maxSession 2

Now run above test from testng.xml file. It will launch 2 browsers to
run both software automation test cases parallel. Other 2 pending
requests on node will wait for current session to be closed as bellow.

But here you know, We have commented driver.quit(); from both test
cases so tests will be executed successfully on both driver instances but
driver instances will not closed. It will remain as it is for 5 minutes
(node default timeout period) so remaining 2 tests will stay in queue for
5 minutes as no slot is free on node to run test. When default timeout
time reached, both current driver instances will be closed and then
remaining two requests will start execution by launching new driver
instances on node.
Running test with timeout for node
To reset node timeout, We can use timeout parameter when launching
node. You can set your desired timeout for node so that it can start
next test if driver instance stay steady for given time. Let's configure
node with timeout to check how it works in above scenario.

Restart grid hub.

Restart grid node using bellow command. Here we have used timeout 20000 (20 seconds) at the end of command. You can set
timeout as per your requirement.
Note : Meaning of -timeout 20000 : During test execution if browser
will remain steady for 20 seconds, Node will close it immediately after
20 seconds.

java -jar selenium-server-standalone-2.52.0.jar -role node


-Dwebdriver.ie.driver="D:/IEDriverServer.exe"
-Dwebdriver.chrome.driver="D:/chromedriver.exe" -hub
http://localhost:4444/grid/register -port 5566 -browser
browserName=firefox,maxInstances=2 -browser browserName=chrome,maxInstances=2
-browser browserName=iexplore,maxInstances=2 -maxSession 2 -timeout 20000

Now run above tests from testng.xml file. Both software automation
tests will be executed, then browsers will stay steady for 20 seconds
and then both of them will be closed automatically and new requests
will start execution on free slots.
This way, node timeout can help you to close browser instance if it is
stuck during test execution.

Running Multiple Nodes Of Selenium


Grid On Same Machine To Run
WebDriver Test
Earlier we learnt, How to start single node on one machine as described
in THIS POST. Now our next question is "can we run multiple
selenium grid nodes on same machine?". Answer is yes. Selenium
grid allows us to runmultiple nodes on same machine. In general, It
is not required to run multiple nodes on same machine as we can
control number of browsers as described in THIS POST and number of
browser sessions in THIS POST. So it is easy to configure one node on
one machine and run test on it as per requirements. But still let's see
an example of running multiple nodes on same machine.
As you know, Selenium grid node is using port to listen request from
hub and send response back. Till now, We have used 5566 port to run
node in all previous examples of selenium grid. So if one node is
already running on 5566 port and you wants to start 2nd node on same
machine then you need to use other post 5567 as we can run only one
node per port number. Let's start one hub and 2 nodes on same
machine and run tests on both of them.
Start selenium grid hub
Start selenium grid hub as described in THIS POST.
Register selenium grid node 1
Open command prompt and run bellow given command in it to start
1st node. It will configure node 1 to run 2 Firefox and 2 chrome
browser instances but max 2 instances at a time.
java -jar selenium-server-standalone-2.52.0.jar -role node
-Dwebdriver.ie.driver="D:/IEDriverServer.exe"
-Dwebdriver.chrome.driver="D:/chromedriver.exe" -hub
http://localhost:4444/grid/register -port 5566 -browser
browserName=firefox,maxInstances=2 -browser browserName=chrome,maxInstances=2
-maxSession 2

Register selenium grid node 2

Open another command prompt and run bellow given command in it


to start 2nd node. It will configure node 2 to run 2 Firefox and 2
chrome browser instances but max 2 instances at a time.
java -jar selenium-server-standalone-2.52.0.jar -role node
-Dwebdriver.ie.driver="D:/IEDriverServer.exe"
-Dwebdriver.chrome.driver="D:/chromedriver.exe" -hub
http://localhost:4444/grid/register -port 5567 -browser
browserName=firefox,maxInstances=2 -browser browserName=chrome,maxInstances=2
-maxSession 2

Check both nodes running properly or not


Now if you access URL : http://localhost:4444/grid/console , It will show
you both nodes running on different ports as shown in bellow given
image. That means your nodes are registered with hub and ready to
use.

Create and run tests on both nodes of grid


We can use test cases of "timeout" test in this example.

Create test cases(fillingForm.java and Calc.java) and testng.xml


files as described in PREVIOUS POST.

un-comment driver.quit(); from both test cases.


Now run tests from testng.xml file. It will launch 4 browsers instances(2
instances on each node) and start executing tests on it.
If you refresh grid console page during test execution, it will show you
that 2 sessions are running on node 1 and 2 sessions are running on
node 2 as shown in bellow image.

This way we can run multiple nodes on same machine to execute


selenium webdriver tests.
Note : I don't know if this is incorrect way but i know it is possible and
it runs your tests on both nodes. I tried it and works for me so i have
shared this info with you. Let me know if anyone of you face any issue
in this combination.

Launch Selenium Grid Hub And Nodes


Using "JSON" Config File
What is JSON?
"JavaScript Object Notation" is full form of JSON and it is best way to
store information in an organized, easy-to-access and easy to read and
understand manner. Here we can use it to store selenium grid config
parameters.
What is usage of JSON in selenium grid?
Well.. Answer is : When we start selenium grid hub and
nodesmanually from command prompt, We need to set many different
parameters for grid hub and nodes like port, browserName,
maxInstances, platform, maxSession etc.. from command prompt. You
will find all config parameter's example links on Selenium Grid
tutorialpage. Instead of feeding all config parameters directly from
command prompt, We can store selenium grid hub and nodes config
parameters in .json file and then can use that file to start hub and
nodes with required configuration.

Let's learn it practically how to create .json files for selenium grid hub
and node and then how to run them.
Scenario : Consider example of "maxSession" as described on Usage
of maxSession. We wants to run 2 test cases on 2 different
browsers(Firefox and Chrome) but max 2 sessions at a time using
selenium grid.
Creating .json file for selenium grid hub
Follow the steps given bellow to create GridHub.json file.

Create new notepade(.txt) file.

Copy-paste bellow given code in it.


{
"host": null,
"port": 4444,
"newSessionWaitTimeout": -1,
"servlets" : [],
"prioritizer": null,
"capabilityMatcher":
"org.openqa.grid.internal.utils.DefaultCapabilityMatcher",
"throwOnCapabilityNotPresent": true,
"nodePolling": 5000,
"cleanUpCycle": 5000,
"timeout": 300000,
"maxSession": 5
}

Save file with name GridHub.json in D: drive.


Creating .json file for selenium grid node

Follow the steps given bellow to create GridNode.json file.

Create new notepade(.txt) file.

Copy-paste bellow given code in it.


{
"capabilities":
[
{
"browserName": "firefox",
"maxInstances": 2,

"acceptSslCerts": true,
"javascriptEnabled": true,
"platform": "WINDOWS",
"seleniumProtocol": "WebDriver"
},
{
"browserName": "chrome",
"maxInstances": 2,
"platform": "WINDOWS",
"seleniumProtocol": "WebDriver"
}
],
"configuration":
{
"proxy": "org.openqa.grid.selenium.proxy.DefaultRemoteProxy",
"maxSession": 2,
"port": 5555,
"host": ip,
"register": true,
"registerCycle": 5000,
"hubPort": 4444,
"hubHost": ip
}
}

Save file with name GridNode.json in D: drive.


Note : You can change config parameters like hubPort, maxSession,
browserName, maxInstances etc.. in above given files as per your
requirements.
Start hub and node using JSON files
I hope, selenium server standalone jar file and chromedriver exe file is
already available in your D: drive. If they are not there then download
both files and put in D: drive.

- Start grid hub

Open command prompt.

Navigate to D: drive and run bellow given command.


java -jar selenium-server-standalone-2.52.0.jar -role hub -hubConfig
GridHub.json

Here, -hubConfig GridHub.json will load hub config parameters to


start selenium grid hub.
It will start selenium grid hub.
- Start grid node

Open command prompt.

Navigate to D: drive and run bellow given command.


java -jar selenium-server-standalone-2.52.0.jar -role node
-Dwebdriver.chrome.driver="D:/chromedriver.exe" -nodeConfig GridNode.json

Here, -nodeConfig GridNode.json will load node config parameters to


start selenium grid hub.
It will start selenium grid node.
Now if you access http://localhost:4444/grid/console URL in browser, It
will show you grid configuration with 2 firefox and 2 chrome browsers
as bellow.

Now you are ready to run selenium webdriver test on selenium grid.
Create WebDriver test and run using grid
Create fillingForm.java, Calc.java and testng.xml files in your eclipse as
given in maxSession Example and run test from testng.xml file. It will
start running on grid.

This way you can use JSON file to launch selenoum grid hub and node
configuration.

Vous aimerez peut-être aussi