Sauce lab automatically log bug into jira - automation

We're looking into automation so we're facing the issue is sauce lab automatically logs bugs in Jira of fail test cases?

Yes, Not only does Sauce Labs log failed test cases, we provide analytics and a dashboard to help you understand and find patterns in those failures. You can see an example here of how to add a 'test status' that is passed to the Sauce Labs Dashboard
import org.junit.rules.TestRule;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
//...
private String testName;
private String sessionId;
private SauceREST sauceClient;
// ...
#Override
protected void before() throws Exception {
if (host.equals("saucelabs")) {
MutableCapabilities sauceOptions = new MutableCapabilities();
sauceOptions.setCapability("username", sauceUser);
sauceOptions.setCapability("accessKey", sauceKey);
sauceOptions.setCapability("name", testName);
sauceOptions.setCapability("tunnelIdentifier", "walkerlj_tunnel_id" );
// sauceOptions.setCapability("parentTunnel", "walkerlj");
MutableCapabilities capabilities = new MutableCapabilities();
capabilities.setCapability("browserName", browserName);
capabilities.setCapability("browserVersion", browserVersion);
capabilities.setCapability("platformName", platformName);
capabilities.setCapability("sauce:options", sauceOptions);
String sauceUrl = String.format("https://ondemand.saucelabs.com/wd/hub");
driver = new RemoteWebDriver(new URL(sauceUrl), capabilities);
sessionId = ((RemoteWebDriver) driver).getSessionId().toString();
sauceClient = new SauceREST(sauceUser, sauceKey, DataCenter.US);
// ...
public TestRule watcher;{
// ...
#Override
protected void failed(Throwable throwable, Description description) {
if (host.equals("saucelabs")) {
sauceClient.jobFailed(sessionId);
System.out.println(String.format("https://saucelabs.com/tests/%s", sessionId));
}
}
#Override
protected void succeeded(Description description) {
if (host.equals("saucelabs")) {
sauceClient.jobPassed(sessionId);
}
}
};
// ...

Related

Print the Reporter logs of #BeforeMethod and #AfterMethod in emailable report of testng

I am running some cleanup code in the aftermethod of testng. Everything is smooth but the logs are not printed on the emailable report. But it prints on the console.
Is there is any way to print the logs of the before method and after method in the emailable report.html
Providing the sample code
import java.io.IOException;
import java.lang.reflect.Method;
import org.testng.Reporter;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class AutoItTest {
#BeforeMethod(alwaysRun = true)
public void initialize(Method method) {
Reporter.log("Reporter before");
String methodName = method.getName();
int parameterCount = method.getParameterCount();
String className = this.getClass().getCanonicalName();
Reporter.log("methodName: "+methodName);
Reporter.log("parameterCount: "+parameterCount);
Reporter.log("className: "+className);
long threadId = Thread.currentThread().getId();
Reporter.log("threadId before: "+threadId);
Test test = method.getAnnotation(Test.class);
if (test == null) {
return;
}
Reporter.log(test.testName() + " is currently running");
Reporter.log(test.description() + " was its description");
}
#AfterMethod(alwaysRun = true)
public void uninitialize(Method method) {
Reporter.log("Reporter after");
String methodName = method.getName();
int parameterCount = method.getParameterCount();
String className = this.getClass().getCanonicalName();
long threadId = Thread.currentThread().getId();
Reporter.log("threadId after: "+threadId);
Reporter.log("methodName: "+methodName);
Reporter.log("parameterCount: "+parameterCount);
Reporter.log("className: "+className);
}
#Test(groups = "vdi")
public void VDITest() throws IOException, Exception {
Reporter.log("VDITest");
Reporter.log("Reporter VDITest");
long threadId = Thread.currentThread().getId();
Reporter.log("threadId VDITest: "+threadId);
}
#Test(groups = "vdi")
public void VDITest123() throws IOException, Exception {
Reporter.log("VDITest123");
long threadId = Thread.currentThread().getId();
Reporter.log("threadId VDITest123: "+threadId);
}
}
I want to integrate somehow the beforemethod and aftermethod logs
I have found the answer
#AfterMethod
public void reportTest(ITestResult result) {
Reporter.setCurrentTestResult(result);
Reporter.log("Message to be printed");
}
I have added Reporter.setCurrentTestResult(result); in both #BeforeMethod and #AfterMethod and the consecutive logs printed on the emailable report.

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

Responce time for steps (WebDriver + Jmeter)

I have a test, where I:
Go to the link
Input Login and Password and press Login button
Press Some link
Press LogOut button
I run it in JMeter with 5 users, and I should save some data in csv file, like:
UserName, Login (or smth from 4 steps about), Average time.
In output I should have a file where I can see, that 5 user do step "Login" for average time (5 second for example). How to know average time - find all steps "Login" plus all time and divide on user count (5)?
Implement it in JMeter as follows:
WebDriver Sampler with Label Go to the link
WebDriver Sampler with label Login
WebDriver Sampler with label Navigate
WebDriver Sampler with label Logout
WebDriver code for each sampler should look as follows:
WDS.sampleResult.sampleStart()
// put code for login, navigate, logout, etc.
WDS.sampleResult.sampleEnd()
WebDriver session will remain between samplers and JMeter is smart enough to measure average response times, just add a relevant listener, i.e. Aggregate Report
See The WebDriver Sampler: Your Top 10 Questions Answered guide for more tips and tricks.
No, it's not passed for me, I use JUnit. Here's my code:
public class LoadTestTwo extends TestCase {
private WebDriver driver;
public FirefoxProfile profile = new FirefoxProfile();
public int index=0;
private long start;
private long end;
boolean alreadyExists = new File("C:\\output.csv").exists(); //write estimate time to file
public LoadTestTwo(){
reset();
//start = System.currentTimeMillis();
}
public void end(){
end = System.currentTimeMillis();
}
public long duration(){
return (end-start);
}
public void reset(){
start = 0;
end = 0;
}
public LoadTestTwo(String testName){
super(testName);
}
#Before
public void setUp() throws Exception {
super.setUp();
}
#Test
public void testTestLoad() throws InterruptedException, IOException, FileNotFoundException {
LoadTestTwo t = new LoadTestTwo();
try {
CsvWriter csvOutput = new CsvWriter(new FileWriter("C:\\output.csv",true),',');
if (!alreadyExists) {
csvOutput.write("Users");
csvOutput.write("Steps");
csvOutput.write("Average Time");
csvOutput.endRecord();
}
driver = new FirefoxDriver();
t.reset();
start = System.currentTimeMillis();
driver.get("somelink"); //just hided the real link
t.end();
csvOutput.write("LoadTest2");
csvOutput.write("Go to URL");
csvOutput.write("" + t.duration());
csvOutput.endRecord();
t.reset();
start = System.currentTimeMillis();
start = System.currentTimeMillis();
driver.findElement(By.id("loginForm:authLogin")).sendKeys("User1");
driver.findElement(By.id("loginForm:authPassword")).sendKeys("123456");
driver.manage().timeouts().implicitlyWait(60, TimeUnit.MILLISECONDS);
driver.findElement(By.id("loginForm:btnLogin")).click();
t.end();
csvOutput.write("LoadTest2");
csvOutput.write("Login");
csvOutput.write("" + t.duration());
csvOutput.endRecord();
driver.manage().timeouts().implicitlyWait(4000, TimeUnit.MILLISECONDS);
t.reset();
start = System.currentTimeMillis();
driver.findElement(By.className("log")).click();
t.end();
driver.manage().timeouts().implicitlyWait(5000, TimeUnit.MILLISECONDS);
csvOutput.write("LoadTest2");
csvOutput.write("Go to Administration");
csvOutput.write("" + t.duration());
csvOutput.endRecord();
driver.manage().timeouts().implicitlyWait(7000, TimeUnit.MILLISECONDS);
t.reset();
start = System.currentTimeMillis();
driver.findElement(By.xpath("//a[#class='logout']")).click();
t.end();
csvOutput.write("LoadTest2");
csvOutput.write("Logout");
csvOutput.write("" + t.duration());
csvOutput.endRecord();
/*FileReader fr = new FileReader(new File("C:\\output.csv"));
BufferedReader br = new BufferedReader(fr);
String st;
while ((st = br.readLine()) != null){
System.out.println(st);
}*/
csvOutput.close();
} catch (IOException e) {
e.printStackTrace();
}
}
#After
public void tearDown() throws Exception {
super.tearDown();
driver.quit();
}
}
Here's just one user, I'll make 5 Jar files and start it in JMeter.

how to get the number of busy selenium hub slots

Is there a way to get the number of busy slots on a selenium hub?
I only know the hub console url (/grid/console), there I can parse the html code ... but this is quite ugly, and quite slow if there are many slots.
Maybe somebody knows a better way?
thanks,
Alex.
This is an old question but perhaps this solution help others.
You can extend org.openqa.grid.web.servlet.RegistryBasedServlet, inject it to the hub and get information via http/json
This is the code for the class:
import java.io.IOException;
import java.util.Iterator;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.openqa.grid.common.exception.GridException;
import org.openqa.grid.internal.ProxySet;
import org.openqa.grid.internal.Registry;
import org.openqa.grid.internal.RemoteProxy;
import org.openqa.grid.internal.TestSlot;
import org.openqa.grid.web.servlet.RegistryBasedServlet;
import org.openqa.selenium.Platform;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import com.google.gson.JsonArray;
import com.google.gson.JsonIOException;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
public class NodesInfoServlet extends RegistryBasedServlet {
private static final long serialVersionUID = -5559403361498232207L;
public NodesInfoServlet() {
super(null);
}
public NodesInfoServlet(Registry registry) {
super(registry);
}
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
process(req, resp);
}
protected void process(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/json");
response.setCharacterEncoding("UTF-8");
response.setStatus(200);
JsonObject res;
try {
res = getFreeBrowsers();
response.getWriter().print(res);
response.getWriter().close();
} catch (JsonIOException e) {
throw new GridException(e.getMessage());
}
}
private JsonObject getFreeBrowsers() throws IOException, JsonIOException {
JsonObject requestJSON = new JsonObject();
ProxySet proxies = this.getRegistry().getAllProxies();
JsonObject platformsbrowsers = new JsonObject();
for (RemoteProxy proxy : proxies) {
for (TestSlot slot : proxy.getTestSlots()) {
if (slot.getSession() == null){
// Plataforma del slot
Platform ptf = getPlatform(slot);
if (ptf != null){
JsonArray browserlist = new JsonArray();
if (!platformsbrowsers.has(ptf.toString())){
platformsbrowsers.add(ptf.toString(), browserlist);
}
JsonArray platform = platformsbrowsers.getAsJsonArray(ptf.toString());
// Browser del slot
DesiredCapabilities cap = new DesiredCapabilities(slot.getCapabilities());
JsonPrimitive browser = new JsonPrimitive(cap.getBrowserName());
if (!platform.contains(browser)){
platform.add(browser);
}
}
}
}
}
requestJSON.add("PlatformsBrowsers", platformsbrowsers);
return requestJSON;
}
private static Platform getPlatform(TestSlot slot) {
Object o = slot.getCapabilities().get(CapabilityType.PLATFORM);
if (o == null) {
return Platform.ANY;
} else {
if (o instanceof String) {
return Platform.valueOf((String) o);
} else if (o instanceof Platform) {
return (Platform) o;
} else {
throw new GridException("Cannot cast " + o + " to org.openqa.selenium.Platform");
}
}
}
}
You need to inject in the hub:
java -classpath C:\Selenium\selenium-server-standalone.jar;C:\Selenium\NodesInfoServlet.jar; org.openqa.grid.selenium.GridLauncher -role hub -hubConfig hubConfig.json -servlets NodesInfoServlet
You get the results via http:
http://localhost:4444/grid/admin/NodesInfoServlet
Result:
{
PlatformsBrowsers: {
VISTA: [
"internet explorer",
"phantomjs",
"htmlunit"
]
}
}
Hope this helps!!!
What I researched so far, the Selenium API is not providing a method to get the hub information from the client side. It is pretty ugly to parse the source code but that is working for me. Other people mentioned to make some changes to the selenium hub jar file but that won't be scalable and it will be needed with each selenium version. (Firefox versions and Selenium versions are all the time changing... I wouldn't recommend you to do that)
If you are using Java, you can try to use Json simple to parse the string and get easily the browsers.
https://code.google.com/p/json-simple/
I hope this can be helpful.

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;
}
}