Setup proxy in Firefox browser via marionette driver - selenium

Firefox 47 and above do not support Selenium Webdriver. I tried to use a Marionette driver to start my tests via Firefox.
But my settings in firefox-profile (proxy must set to network.proxy.type = 4, auto-detect) is no longer applied to Firefox config (Firefox opens but all settings set by default) and my tests do not work without the right PROXY configuration.
How can I setup proxy in Firefox browser via a Marionette driver?

The old tricks with firefoxProfile or Proxy class do not work any more. All you have to do is pass through requiredCapabilities a JSON with the new Marionette proxy format:
[{proxy={"proxyType":"MANUAL","httpProxy":"host.proxy","httpProxyPort":80,"sslProxy":"host.proxy","sslProxyPort":80}}]
No more "proxyHost:proxyPort" format, but httpProxy=host, httpProxyPort=port.
JsonObject json = new JsonObject();
json.addProperty("proxyType", "MANUAL");
json.addProperty("httpProxy", aHost);
json.addProperty("httpProxyPort", aPort);
json.addProperty("sslProxy", aHost);
json.addProperty("sslProxyPort", aPort);
required.setCapability("proxy", json);
driver = new FirefoxDriver(service, cap, required);
Here is all the code:
import java.io.File;
import java.io.IOException;
import org.apache.commons.lang.SystemUtils;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxBinary;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.GeckoDriverService;
import org.openqa.selenium.remote.DesiredCapabilities;
import com.google.common.collect.ImmutableMap;
import com.google.gson.JsonObject;
public class TestProxy
{
public static void main(String[] args)
{
if (args.length == 0)
{
System.out.println("usage: IP port");
System.exit(-1);
}
String proxyServer = args[0];
int proxyPort = Integer.parseInt(args[1]);
try
{
TestProxy test = new TestProxy();
test.TestDriver(proxyServer, proxyPort);
} catch (IOException e)
{
e.printStackTrace();
}
}
private void TestDriver(String aHost, int aPort) throws IOException
{
WebDriver driver = null;
GeckoDriverService service = null;
if (SystemUtils.IS_OS_LINUX)
{
FirefoxBinary firefoxBinary = new FirefoxBinary(new File("/home/ubuntu/firefox/firefox"));
service = new GeckoDriverService.Builder(firefoxBinary)
.usingDriverExecutable(new File("/usr/bin/geckodriver"))
.usingAnyFreePort()
.usingAnyFreePort()
.withEnvironment(ImmutableMap.of("DISPLAY",":20"))
.build();
service.start();
}
else if (SystemUtils.IS_OS_WINDOWS)
{
FirefoxBinary firefoxBinary = new FirefoxBinary(new File("C:\\Program Files\\Mozilla Firefox\\firefox.exe"));
service = new GeckoDriverService.Builder(firefoxBinary)
.usingDriverExecutable(new File("C:\\Windows\\geckodriver.exe"))
.usingAnyFreePort()
.usingAnyFreePort()
.build();
service.start();
}
else
{
System.out.println("Unknown operation system");
System.exit(-1);
}
DesiredCapabilities cap = DesiredCapabilities.firefox();
DesiredCapabilities required = new DesiredCapabilities();
JsonObject json = new JsonObject();
json.addProperty("proxyType", "MANUAL");
json.addProperty("httpProxy", aHost);
json.addProperty("httpProxyPort", aPort);
json.addProperty("sslProxy", aHost);
json.addProperty("sslProxyPort", aPort);
required.setCapability("proxy", json);
driver = new FirefoxDriver(service, cap, required);
driver.navigate().to("https://api.ipify.org/?format=text");
System.out.println(driver.getPageSource());
driver.quit();
}
}
https://github.com/SeleniumHQ/selenium/issues/2963
https://github.com/mozilla/geckodriver/issues/97#issuecomment-255386464

Related

Junit 5 tests are not running in parallel

I have created a simple program to intialte crome and one SYSO statement. I want to run the 2 #Test in parallel. But it is executing alwasy is seq. What could be teh reason for it to not recognise the parallel execution?
Here is the code:
import static org.junit.jupiter.api.Assertions.*;
import java.util.HashMap;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.parallel.Execution;
import org.junit.jupiter.api.parallel.ExecutionMode;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.Proxy.ProxyType;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;
#Execution(ExecutionMode.CONCURRENT)
public class Parallel {
static String driverPath = "C:/BestX/workspace/chromedriver_win32/chromedriver.exe";
static String downloadFilepath = "C:\\BestX";
#Execution(ExecutionMode.CONCURRENT)
#Test
void test1() throws Exception {
createDriver();
Thread.sleep(5000);
System.out.println(Thread.currentThread().getName()+" => test1"); //.currentThread.getName() -just to display current running thread name
}
#Execution(ExecutionMode.CONCURRENT)
#Test
void test2() throws Exception {
createDriver();
Thread.sleep(5000);
System.out.println(Thread.currentThread().getName()+" => test1"); //.currentThread.getName() -just to display current running thread name
}
public void createDriver() {
DesiredCapabilities dcaps = new DesiredCapabilities();
dcaps.setCapability("takesScreenshot", true);
System.setProperty("webdriver.chrome.driver", driverPath);
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments(new String[] { "--no-sandbox" });
chromeOptions.addArguments(new String[] { "--max_old_space_size=4096" });
dcaps.setCapability("goog:chromeOptions", chromeOptions);
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("download.default_directory", downloadFilepath);
chromeOptions.setAcceptInsecureCerts(true);
chromeOptions.setExperimentalOption("prefs", chromePrefs);
WebDriver driver = new ChromeDriver(chromeOptions);
driver.manage().window().setSize(new Dimension(1920, 1200));
}
}
'''
and here is the "junit-platform.properties" under resource folder
junit.jupiter.execution.parallel.enabled = true
junit.jupiter.execution.parallel.mode.default = concurrent
It is workign now. Was a silly mistake in folder structure. The junit-platform.properties file was under tests->resources instead of test->resources folder

How to run the testng test methods parallel?

I am trying to run the test methods in parallel by using TestNg concept, but it's not working as expected. It's launching multiple browsers and creating each thread for each browser, but it's entering all the value in only one browser. Please help me out. Here browser object and extent reports object are thread safe. Please find the test methods.
This is the Test class that needs to be executed in parallel, but it's not working. It just launches multiple browsers and all the thread value feeding data to one browser itself.
package com.sonata.tests;
import java.util.Map;
import java.util.Properties;
import org.testng.SkipException;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import com.sonata.utility.DataReader;
import com.sonata.utility.DriverCreation;
import com.sonata.pages.ComplaintPage;
import com.sonata.pages.HomePage;
import com.sonata.pages.LoginPage;
public class ComplainTest extends DriverCreation {
private String browser;
private String url;
HomePage homeObject;
LoginPage loginObject;
ComplaintPage compObject;
DataReader dataReader = new DataReader();
#Parameters({ "url", "browser" })
#BeforeMethod
public void readProperties(String url, String browser) {
/*
* Properties prop = PropertiesReader.getProperty(); browser =
* prop.getProperty("browser.name"); url = prop.getProperty("app.url");
*/
this.browser = browser;
this.url = url;
}
#Test
public void createComplaintCaseWithDefault() {
setTestCaseName("TC-10672");
initExtent(testCaseName);
if (!dataReader.isTestCaseExecute(xlsReader, testCaseName)) {
logger.info("Test Case not executed as its run mode is NO");
throw new SkipException("");
}
Object[][] testData = dataReader.getTestData(xlsReader, testCaseName);
for (int t = 0; t < testData.length; t++) {
initDriver(browser);
homeObject = new HomePage(driver, report, wait, logger);
homeObject.goToHomepge(url);
#SuppressWarnings("unchecked")
Map<String, String> testDataMap = (Map<String, String>) testData[t][0];
loginObject = new LoginPage(driver, report, wait, logger);
loginObject.login(testDataMap.get("UserName"),
testDataMap.get("Password"));
compObject = new ComplaintPage(driver, report, wait, logger);
compObject.createCase(testDataMap.get("ComplaintType"),
testDataMap.get("CustomerName"),
testDataMap.get("ComplaintCategory"));
compObject.complaintPageVerification();
}
}
#Test
public void createComplaintCaseWithSensitive() {
setTestCaseName("TC-10692");
initExtent(testCaseName);
if (!dataReader.isTestCaseExecute(xlsReader, testCaseName)) {
logger.info("Test Case not executed as its run mode is NO");
throw new SkipException("");
}
Object[][] testData = dataReader.getTestData(xlsReader, testCaseName);
for (int t = 0; t < testData.length; t++) {
initDriver(browser);
homeObject = new HomePage(driver, report, wait, logger);
homeObject.goToHomepge(url);
#SuppressWarnings("unchecked")
Map<String, String> testDataMap = (Map<String, String>) testData[t][0];
loginObject = new LoginPage(driver, report, wait, logger);
loginObject.login(testDataMap.get("UserName"),
testDataMap.get("Password"));
compObject = new ComplaintPage(driver, report, wait, logger);
compObject.createCase(testDataMap.get("ComplaintType"),
testDataMap.get("CustomerName"),
testDataMap.get("ComplaintCategory"));
compObject.complaintPageVerification();
}
}
#Test
public void reopenComplaintFieldVerfication() {
setTestCaseName("TC-10958");
initExtent(testCaseName);
if (!dataReader.isTestCaseExecute(xlsReader, testCaseName)) {
logger.info("Test Case not executed as its run mode is NO");
throw new SkipException("");
}
Object[][] testData = dataReader.getTestData(xlsReader, testCaseName);
for (int t = 0; t < testData.length; t++) {
initDriver(browser);
homeObject = new HomePage(driver, report, wait, logger);
homeObject.goToHomepge(url);
#SuppressWarnings("unchecked")
Map<String, String> testDataMap = (Map<String, String>) testData[t][0];
loginObject = new LoginPage(driver, report, wait, logger);
loginObject.login(testDataMap.get("UserName"),
testDataMap.get("Password"));
compObject = new ComplaintPage(driver, report, wait, logger);
compObject.reopenReasonFieldVerification(testDataMap
.get("ComplaintID"));
}
}
#AfterMethod
public void closeBrowser() {
if (driver != null) {
homeObject.tearDownTest();
}
if (report != null) {
report.endTest();
}
}
}
This is the Driver class which will create the driver instance for each Test method.
package com.sonata.utility;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriverService;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.LogStatus;
import com.sonata.constants.Constants;
public class DriverCreation {
public ExtentReports report;
public WebDriver driver;
public DesiredCapabilities cap1;
public WebDriverWait wait;
protected String testCaseName;
ExtentReport extent;
public Logger logger = Logger.getLogger(this.getClass().toString());
public ExcelReader xlsReader = new ExcelReader(getProjectPath()
+ Constants.XLS_FILE_PATH);
/*
* public DriverCreation(String browser,ExtentReports report,Logger logger){
* this.browser = browser; this.report = report; this.logger = logger; }
*/
public void initExtent(String reportName) {
extent = new ExtentReport();
report = extent.getExtentReportInstance(reportName);
}
public void setTestCaseName(String testCaseName){
this.testCaseName = testCaseName;
}
public WebDriver initDriver(String browser) {
try {
cap1 = new DesiredCapabilities();
if (!Constants.CONSTANTS_GRIDEXECUTION) {
if (browser.equalsIgnoreCase("Firefox")) {
System.setProperty("webdriver.gecko.driver",
Constants.CONSTANTS_GECKO_DRIVER_PATH);
cap1.setCapability("marionette", true);
/* ThreadLocal<WebDriver> driver1 = new ThreadLocal<WebDriver>(){
#Override
protected WebDriver initialValue(){
return new FirefoxDriver(cap1);
}
};*/
//driver = driver1.get();*/
driver= new FirefoxDriver(cap1);
driver.manage().timeouts()
.implicitlyWait(2, TimeUnit.SECONDS);
wait = new WebDriverWait(driver, 50);
report.log(LogStatus.INFO, "Firefox driver has started");
logger.info("Firefox driver has started");
} else if (browser.equalsIgnoreCase("Chrome")) {
System.setProperty(Constants.CONSTANTS_CHROME_PROPERTY,
Constants.CONSTANTS_CHROME_DRIVER_PATH);
/*driver1 = new ThreadLocal<WebDriver>(){
#Override
protected WebDriver initialValue(){
return new ChromeDriver();
}
};
driver = driver1.get();*/
driver = new ChromeDriver();
driver.manage().timeouts()
.implicitlyWait(2, TimeUnit.SECONDS);
wait = new WebDriverWait(driver, 50);
report.log(LogStatus.INFO, "Chrome driver has started");
logger.info("Chrome driver has started");
} else if (browser.equalsIgnoreCase("PhantomJS")) {
System.setProperty(Constants.CONSTANTS_PHANTOM_PROPERTY,
Constants.CONSTANTS_PHANTOM_DRIVER_PATH);
cap1.setJavascriptEnabled(true);
cap1.setCapability("takesScreenshot", true);
cap1.setCapability(
PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,
Constants.CONSTANTS_PHANTOM_DRIVER_PATH);
/*ThreadLocal<WebDriver> driver1 = new ThreadLocal<WebDriver>(){
#Override
protected WebDriver initialValue(){
return new PhantomJSDriver(cap1);
}
};
driver = driver1.get();*/
driver = new PhantomJSDriver(cap1);
driver.manage().window().setSize(new Dimension(1920, 1200));
wait = new WebDriverWait(driver, 50);
report.log(LogStatus.INFO,
"PhantomJS/Ghost driver has started");
logger.info("PhantomJS/Ghost driver has started");
} else if (browser.equalsIgnoreCase("IE")) {
System.setProperty(Constants.CONSTANTS_IE_PROPERTY,
Constants.CONSTANTS_IE_DRIVER_PATH);
// cap1.internetExplorer();
cap1.setCapability(
InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION,
true);
/*ThreadLocal<WebDriver> driver1 = new ThreadLocal<WebDriver>(){
#Override
protected WebDriver initialValue(){
return new InternetExplorerDriver(cap1);
}
};
driver = driver1.get();*/
driver = new InternetExplorerDriver(cap1);
driver.manage().timeouts()
.implicitlyWait(2, TimeUnit.SECONDS);
wait = new WebDriverWait(driver, 50);
report.log(LogStatus.INFO,
"Internet Explorer driver has started");
logger.info("Internet Explorer driver has started");
}
} else {
String nodeUrl = Constants.CONSTANTS_IPDETAILS;
if (browser.equalsIgnoreCase("Firefox")) {
System.setProperty("webdriver.gecko.driver",
Constants.CONSTANTS_GECKO_DRIVER_PATH);
cap1.setCapability("marionette", true);
cap1 = DesiredCapabilities.firefox();
cap1.setBrowserName("firefox");
cap1.setPlatform(Platform.WINDOWS);
} else if (browser.equalsIgnoreCase("Chrome")) {
System.setProperty(Constants.CONSTANTS_CHROME_PROPERTY,
Constants.CONSTANTS_CHROME_DRIVER_PATH);
cap1 = DesiredCapabilities.chrome();
cap1.setBrowserName("chrome");
cap1.setPlatform(Platform.WINDOWS);
} else if (browser.equalsIgnoreCase("IE")) {
System.setProperty(Constants.CONSTANTS_IE_PROPERTY,
Constants.CONSTANTS_IE_DRIVER_PATH);
// cap1.internetExplorer();
cap1 = DesiredCapabilities.internetExplorer();
cap1.setBrowserName("internet explorer");
cap1.setPlatform(Platform.WINDOWS);
cap1.setCapability(
InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,
true);
cap1.setCapability(
InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION,
true);
}
ThreadLocal<WebDriver> driver1 = new ThreadLocal<WebDriver>(){
#Override
protected WebDriver initialValue(){
try {
return new RemoteWebDriver(new URL(nodeUrl), cap1);
} catch (MalformedURLException e) {
e.printStackTrace();
}
return null;
}
};
driver = driver1.get();
driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
wait = new WebDriverWait(driver, 50);
report.log(LogStatus.INFO, browser + " driver has started");
logger.info(browser + " driver has started");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
Assert.assertTrue(true, "Set up Test");
} catch (Exception e) {
logger.error("Try and catch block while assert " + e);
}
}
return driver;
}
private String getProjectPath() {
File currentDirFile = new File("");
String path = currentDirFile.getAbsolutePath();
return path;
}
}
TESTNG SUITE XML:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="C4C" thread-count="3" parallel="methods">
<parameter name="url" value="https://abc.xyz.ondemand.com/"/>
<parameter name="browser" value="Chrome"/>
<test name="Case" allow-return-values="true" group-by-instances="true">
<classes>
<class name="com.sonata.tests.ComplainTest" >
</class>
</classes>
</test>
</suite>
You are storing the driver at class level. But you parallelise based on methods. In this case one driver object will be there. I see the thread local lines were commented.
There are two ways to solve this issue,
One: As your running in method level and navigating the HomePage in each method, you can maintain driver object in method level,
Webdriver driver = initDriver(browser);
homeObject = new HomePage(driver, report, wait, logger);
homeObject.goToHomepge(url);
Other way: you can maintain the driver object in thread local in your driver creation class,
public class DriverCreation {
private static ThreadLocal<WebDriver> WEBDRIVER = new ThreadLocal<WebDriver>();
public WebDriver getWebDriver(String browser){
WebDriver driver= WEBDRIVER.get();
if (driver== null) {
driver = initDriver(browser);
WEBDRIVER.set(driver);
}
return driver;
}
}
And use it in test method in same way,
Webdriver driver = getWebDriver(browser);
homeObject = new HomePage(driver, report, wait, logger);
homeObject.goToHomepge(url);
The second one will create only one driver per thread while first one will create one driver per method. Handle the driver quit accordingly

How to register multiple nodes to the hub in selenium grid

Need to register multiple nodes to the hub, Any help in this regards will be appreciated.Selenium grid to be performed with the same driver object.
This is how my code looks like.
Deriving the class using RemoteWebDriver for Hub instance.
import java.net.URL;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import com.project.pages.ExcelConstants;
public class DriverInitializer {
private WebDriver driver = null;
public WebDriver getWebDriverFactory() {
return this.driver;
}
/**
* Returns WebDriver Instance Depending on Parameters browser and Grid d
*
* #param browser
* #param grid
* #return
*/
public WebDriver getDriver(String browser, String grid) {
if (grid.equals("y")) {
getWebDriverRemote(browser);
} else if (grid.equals("n")) {
getWebDriverLocal(browser);
}
return driver;
}
/**
* Creates Local WebDriver Instance
*
* #param browser
* #return
*/
public WebDriver getWebDriverLocal(String browser) {
try {
if (browser.equalsIgnoreCase("chrome")) {
System.setProperty("webdriver.chrome.driver",
System.getProperty("user.dir")
+ "\\Drivers\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("excludeSwitches",
Arrays.asList("ignore-certificate-errors"));
driver = new ChromeDriver(options);
return driver;
}
if (browser.equalsIgnoreCase("ie")) {
System.setProperty("webdriver.ie.driver",
System.getProperty("user.dir")
+ "\\drivers\\IEDriverServer.exe");
DesiredCapabilities cap = DesiredCapabilities
.internetExplorer();
cap.setCapability(
InternetExplorerDriver.UNEXPECTED_ALERT_BEHAVIOR,
"accept");
cap.setCapability("nativeEvents", true);
cap.setCapability(InternetExplorerDriver.INITIAL_BROWSER_URL,
ExcelConstants.TEST_URL_2);
cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
cap.setCapability(
InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,
true);
return driver = new InternetExplorerDriver(cap);
}
if (browser.equals("firefox")) {
System.setProperty("webdriver.gecko.driver",
System.getProperty("user.dir")
+ "\\Drivers\\geckodriver.exe");
// Extra code added
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("acceptInsecureCerts", true);
// Extra code ended
return driver = new FirefoxDriver(capabilities);
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
return driver;
}
/**
* Creates Remote WebDriver Instance
*
* #param browser
* #return
*/
public WebDriver getWebDriverRemote(String browser) {
DesiredCapabilities cap = null;
try {
if (browser.equals("ie")) {
cap = DesiredCapabilities.internetExplorer();
cap.setCapability(
InternetExplorerDriver.UNEXPECTED_ALERT_BEHAVIOR,
"accept");
cap.setCapability(InternetExplorerDriver.INITIAL_BROWSER_URL,
ExcelConstants.TEST_URL_2);
cap.setCapability("nativeEvents", true);
cap.setBrowserName("internet explorer");
cap.setPlatform(Platform.ANY);
}
if (browser.equals("firefox")) {
cap = DesiredCapabilities.firefox();
cap.setCapability(
InternetExplorerDriver.UNEXPECTED_ALERT_BEHAVIOR,
"accept");
cap.setBrowserName("firefox");
cap.setPlatform(Platform.ANY);
}
if (browser.equals("chrome")) {
cap = DesiredCapabilities.chrome();
cap.setBrowserName("chrome");
cap.setPlatform(Platform.WINDOWS);
}
driver = new RemoteWebDriver(new URL(ExcelConstants.NODE_URL_1), cap);
} catch (Exception e) {
System.out.println(e.getMessage());
}
return driver;
}
public static void main(String[] args) {
DriverInitializer di = new DriverInitializer();
di.getWebDriverRemote("chrome");
}
/**
* Implicit Wait
*/
public void waitForPageToLoad(WebDriver driver) {
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
}
/**
* Maximizes the window
*/
public void maximizeWindow(WebDriver driver) {
driver.manage().window().maximize();
}
}
I tried using the thread class but unable to implement it using the concept.
download selenium server stand alone jar from here
after that follow below step
1- start hub using below command
java -jar "your selenium serverstand-alone.jar file path here" -role hub
2- now register your first node with hub-
java -jar "your selenium-server-stand-alone.jar file path here" -role node -hub http://localhost:4444/grid/register -port 5556 -browser "browserName=chrome, maxInstances=5"
3- now start 3rd, 4th etc. by just changing -port and browser value
java -jar "your selenium-server-stand-alone.jar file path here" -role node -hub http://localhost:4444/grid/register -port 5558 -browser "browserName=firefox, maxInstances=5"
to execute on node using selenium server use RemoteWebDriver instead of firefox or chrome driver
for more details description follow below tutorial
https://www.guru99.com/introduction-to-selenium-grid.html

Grid concept in Selenium [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have written coding for browser opening with grid concept. I wrote the following code. I need to know its correct or wrong.
properties
----------
HUB=localhost
PORT=4444
Browser = chrome
Url=http://demo.guru99.com/v4/index.php
Code
----
package processor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import org.openqa.selenium.Platform;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
public class Browser {
public static void main(String[] args) throws FileNotFoundException, IOException {
RemoteWebDriver driver;
Properties prop;
prop = new Properties();
prop.load(new FileInputStream("./config.properties"));
String hub = prop.getProperty("HUB");
String port = prop.getProperty("PORT");
String browser = prop.getProperty("Browser");
String url = prop.getProperty("Url");
if (browser.equalsIgnoreCase("chrome") || browser.equalsIgnoreCase("ie")
|| browser.equalsIgnoreCase("firefox")) {
if (browser.equalsIgnoreCase("chrome")) {
try {
DesiredCapabilities dc;
dc = new DesiredCapabilities();
dc.setBrowserName(browser);
dc.setPlatform(Platform.WINDOWS);
System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe");
driver = new ChromeDriver();
System.out.println("Chrome Browser is Initialising..........");
driver.manage().window().maximize();
driver.get(url);
} catch (Exception e) {
System.out.println("Problem Occurred while Initialising Chrome Browser. Check for the Driver Name & Path !!!!!!!!!!");
}
}
if (browser.equalsIgnoreCase("ie")) {
try {
DesiredCapabilities dc;
dc = new DesiredCapabilities();
dc.setBrowserName(browser);
dc.setPlatform(Platform.WINDOWS);
System.setProperty("webdriver.ie.driver", "./Drivers/IEDriverServer.exe");
driver = new InternetExplorerDriver();
System.out.println("Internet Explorer is Initialising..........");
driver.manage().window().maximize();
driver.get(url);
} catch (Exception e) {
System.out.println("Problem Occurred while Initialising Internet Explorer. Check for the Driver Name & Path !!!!!!!!!!");
}
}
if (browser.equalsIgnoreCase("firefox")) {
try {
DesiredCapabilities dc;
dc = new DesiredCapabilities();
dc.setBrowserName(browser);
dc.setPlatform(Platform.WINDOWS);
driver = new FirefoxDriver();
System.out.println("Firefox is Initialising..........");
driver.manage().window().maximize();
driver.get(url);
} catch (Exception e) {
System.out.println("Problem Occurred while Initialising Firefox. Check for the Driver Name & Path !!!!!!!!!!");
}
}
}
else {
System.out.println("Invalid Browser. Check Browser Name in Properties File.......... ");
}
}
}
Kindly see the code and tell me the correct code. Grid Concept i need to apply.
To use selenium with the grid you need to start a Remote webdriver. What you're doing here is starting a local webdriver of types:
driver = new ChromeDriver();
driver = new InternetExplorerDriver();
driver = new FirefoxDriver();
This is not how you request a browser from the grid.
Furthermore, the path to the driver (System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe");) must be supplied to the grid, so you cannot set this in your code here.
You do this as follows:
java -jar selenium-server-standalone-2.53.0.jar -role hub -Dwebdrivers.chrome.driver=chromedriver.exe
What you are currently doing is creating local webdrivers, you are not connecting to the grid at all. Connecting to the grid is done as follows:
driver = new RemoteWebDriver(hub, dc);

Use Selenium with same browser session

import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.support.ui.Select;
public class Test1 {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
System.setProperty("webdriver.ie.driver", "D:/Development/ProgrammingSoftware/Testing/IEDriverServer.exe");
WebDriver driver = new InternetExplorerDriver();
baseUrl = "http://seleniumhq.org/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void test1() throws Exception {
driver.get(baseUrl + "/download/");
driver.findElement(By.linkText("Latest Releases")).click();
driver.findElement(By.linkText("All variants of the Selenium Server: stand-alone, jar with dependencies and sources.")).click();
}
#After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alert.getText();
} finally {
acceptNextAlert = true;
}
}
}
I would like to have the IE with the same session but this code opens always a new instance of IE. How I get this work?
I don't think it is possible to attach driver to an existing session.
If You've done executing a test method and if you want to execute another test method which is present in another class or package, call the method by passing the present driver to it so that you can use the present instance of the driver over there.
This question has been asked several times in the past and the one I'm about to answer is not even close to recent. However I still gonna go ahead and post an answer because recently I've been engulfed with questions related to same browser session. How would I be able to leverage the browser which is already open, so I can continue my test run, rather than restart it from the scratch. It's even painstaking in some cases, after navigating through tons of pages, when you encounter the issue of restarting your Selenium test. Instead I was left wondering "where is the silver bullet?". Finally I saw one of the articles written by "http://tarunlalwani.com/post/reusing-existing-browser-session-selenium/". However still there are a few missing links. So I wanted to unravel it here with the help of a suitable example.
In the following code snippet, I'm trying to launch SeleniumHQ and Clicking Download link in a Selenium session in Chrome browser.
System.setProperty("webdriver.chrome.driver","C:\\Selenium\\chromedriver.exe");
//First Session
ChromeDriver driver = new ChromeDriver();
HttpCommandExecutor executor = (HttpCommandExecutor)
driver.getCommandExecutor();
URL url = executor.getAddressOfRemoteServer();
SessionId session_id = driver.getSessionId();
storeSessionAttributesToFile("Id",session_id.toString());
storeSessionAttributesToFile("URL",url.toString());
driver.get("https://docs.seleniumhq.org/");
WebElement download = driver.findElementByLinkText("Download");
download.click();
If you read the above code, I'm capturing the URL of Selenium remote server and the session id of the current selenium (browser) session and writing it to a properties file.
Now if I need to continue executing in the same browser window/session, despite stopping the current test run, all I need to do is comment the code below the commented First session in the aforementioned code snippet and continuing your tests from the code below:
System.setProperty("webdriver.chrome.driver","C:\\Selenium\\chromedriver.exe");
//First Session
//ChromeDriver driver = new ChromeDriver();
//HttpCommandExecutor executor = (HttpCommandExecutor) driver.getCommandExecutor();
//URL url = executor.getAddressOfRemoteServer();
//SessionId session_id = driver.getSessionId();
//storeSessionAttributesToFile("Id",session_id.toString());
// storeSessionAttributesToFile("URL",url.toString());
// driver.get("https://docs.seleniumhq.org/");
// WebElement download = driver.findElementByLinkText("Download");
// download.click();
//Attaching to the session
String existingSession = readSessionId("Id");
String url1 = readSessionId("URL");
URL existingDriverURL = new URL(url1);
RemoteWebDriver attachToDriver = createDriverFromSession(existingSession, existingDriverURL);
WebElement previousReleases = attachToDriver.findElementByLinkText("Previous Releases");
previousReleases.click();
Now you may have to refactor and rename the driver object (even leaving the name would still work, but I just wanted to differentiate between attaching it to an existing driver and the launching the driver). In the above code block, I continue my tests, after reading and assigning the URL and sessionid and create the driver from session to continue leveraging the browser and session.
Please view the complete code below:
package org.openqa.selenium.example;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.Collections;
import java.util.Properties;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.Command;
import org.openqa.selenium.remote.CommandExecutor;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.HttpCommandExecutor;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.remote.Response;
import org.openqa.selenium.remote.SessionId;
import org.openqa.selenium.remote.http.W3CHttpCommandCodec;
import org.openqa.selenium.remote.http.W3CHttpResponseCodec;
public class AttachingToSession {
public static String SESSION_FILE = "C:\\example\\Session.Properties";
public static Properties prop = new Properties();
public static void main(String[] args) throws Exception {
System.setProperty("webdriver.chrome.driver","C:\\Selenium\\chromedriver.exe");
//First Session
ChromeDriver driver = new ChromeDriver();
HttpCommandExecutor executor = (HttpCommandExecutor) driver.getCommandExecutor();
URL url = executor.getAddressOfRemoteServer();
SessionId session_id = driver.getSessionId();
storeSessionAttributesToFile("Id",session_id.toString());
storeSessionAttributesToFile("URL",url.toString());
driver.get("https://docs.seleniumhq.org/");
WebElement download = driver.findElementByLinkText("Download");
download.click();
//Attaching to the session
String existingSession = readSessionId("Id");
String url1 = readSessionId("URL");
URL existingDriverURL = new URL(url1);
RemoteWebDriver attachToDriver = createDriverFromSession(existingSession, existingDriverURL);
WebElement previousReleases = attachToDriver.findElementByLinkText("Previous Releases");
previousReleases.click();
}
public static RemoteWebDriver createDriverFromSession(final String sessionId, URL command_executor){
CommandExecutor executor = new HttpCommandExecutor(command_executor) {
#Override
public Response execute(Command command) throws IOException {
Response response = null;
if (command.getName() == "newSession") {
response = new Response();
response.setSessionId(sessionId);
response.setStatus(0);
response.setValue(Collections.<String, String>emptyMap());
try {
Field commandCodec = null;
commandCodec = this.getClass().getSuperclass().getDeclaredField("commandCodec");
commandCodec.setAccessible(true);
commandCodec.set(this, new W3CHttpCommandCodec());
Field responseCodec = null;
responseCodec = this.getClass().getSuperclass().getDeclaredField("responseCodec");
responseCodec.setAccessible(true);
responseCodec.set(this, new W3CHttpResponseCodec());
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} else {
response = super.execute(command);
}
return response;
}
};
return new RemoteWebDriver(executor, new DesiredCapabilities());
}
public static void storeSessionAttributesToFile(String key,String value) throws Exception{
OutputStream output = null;
try{
output = new FileOutputStream(SESSION_FILE);
//prop.load(output);
prop.setProperty(key, value);
prop.store(output, null);
}
catch(IOException e){
e.printStackTrace();
}
finally {
if(output !=null){
output.close();
}
}
}
public static String readSessionId(String ID) throws Exception{
Properties prop = new Properties();
InputStream input = null;
String SessionID = null;
try {
input = new FileInputStream(SESSION_FILE);
// load a properties file
prop.load(input);
// get the property value and print it out
System.out.println(prop.getProperty(ID));
SessionID = prop.getProperty(ID);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return SessionID;
}
}