I am executing my code using shell scripting file and as per requirement if i will not pass parameter then my code will execute on my local machine and if i will pass parameter with shell scripting then code should be execute on browser stack. If i am executing with parameter then my code is working fine . But if i am not passing parameter in shell scripting then unable to launch chrome browser because in If condition driver is null. This is my base class
When i am executing shell script without parameter then my execution is going in If condition but unable to launch chrome browser because driver variable is not initialized in if condition . if i am printing driver value then it is showing null.
package com.epath.smoketest.tests;
/**
* Class: Base
* Author: D Albanese
* Creation Date: 4/5/2017
*/
import org.junit.Rule;
import org.junit.rules.ExternalResource;
import org.openqa.selenium.WebDriver;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.LocalFileDetector;
import org.openqa.selenium.remote.RemoteWebDriver;
public class Base {
//-Browser capability passed by CLI argument.
private static String sBrowser;
//-Browser version passed by CLI argument.
private static String sBversion;
//-OS capability passed by CLI argument.
private static String sOsName;
//-OS version capability passed by CLI argument.
private static String sOsVersion;
//-Passing input folder name by CLI argument.
public String sFolderName = "resources";
public static String getExecutionPath;
public static String getResourcePath;
public static WebDriver driver;
public Base(String sBrowser, String sBversion, String sOsName, String sOsVersion,String sFolderName) {
this.sBrowser = sBrowser;
this.sBversion = sBversion;
this.sOsName = sOsName;
this.sOsVersion = sOsVersion;
if(null != sFolderName && ! sFolderName.trim().equals("")) {
this.sFolderName = sFolderName;
}
}
//-Utilizing ExternalResource rule to preserve functionality of #Before and #After annotations in tests
//-ExternalResource rule has before and after methods that execute prior to methods annotated with #Before and #After
#Rule
public ExternalResource resource = new ExternalResource() {
#Override
protected void before() throws Throwable {
//-Use this for local testing
DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability("browser", sBrowser);
caps.setCapability("browser_version", sBversion);
caps.setCapability("os", sOsName);
caps.setCapability("os_version", sOsVersion);
caps.setCapability("folder_name", sFolderName);
caps.setCapability("browserstack.local", "true");
if(sBrowser.length() == 0 && sBversion.length() == 0 && sOsName.length() == 0 && sOsVersion.length() == 0)
{
System.out.println("Inside If Condition ");
//-Load the properties
Properties prop = new Properties();
InputStream input = null;
input = new FileInputStream(System.getProperty("user.home") +
"/epath/services/tests/resources/AutomationData.properties");
prop.load(input);
// getResourcePath=prop.getProperty("resources_path");
getExecutionPath = prop.getProperty("local_resources_path");
System.out.println("Print Execution Path :- " +getExecutionPath);
System.out.println("Print Driver Path :- " + driver);
System.setProperty("webdriver.chrome", "\\\\192.168.10.21\\volume1\\ngage_dev\\engineering\\ngage\testing\\automated\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
} else {
//-Load the properties
System.out.println("Inside else Condtions ");
Properties prop = new Properties();
InputStream input = null;
input = new FileInputStream(System.getProperty("user.home") +
"/epath/services/tests/resources/AutomationData.properties");
prop.load(input);
getResourcePath=prop.getProperty("resources_path");
getExecutionPath = prop.getProperty("resources_path")+sFolderName;
//-Get USERNAME and AUTOMATE_KEY of browser stack
String browserStackUsername = prop.getProperty("browser_stack_username");
String browserStackAutomateKey = prop.getProperty("browser_stack_automate_key");
String URL = "https://" + browserStackUsername + ":" +
browserStackAutomateKey + "#hub-cloud.browserstack.com/wd/hub";
driver = new RemoteWebDriver(new URL(URL), caps);
//-Load the URL to be tested
driver.get(prop.getProperty("test_url"));
//-For local file uploads
((RemoteWebDriver) driver).setFileDetector(new LocalFileDetector());
}
}
#Override
protected void after() {
driver.quit();
}
};
public String getAutomationInputDataPath() {
return this.getExecutionPath;
}
public static String getResourcePathFromPropertiesfile() {
return getResourcePath;
}
}
And this is my test case class where i am calling base class(above class)
public class AddRegisterLAs extends Base {
private Login login;
private Navigation go;
private LearningActivityAdd addLa;
private ImageAdd addImage;
private DocumentAdd addDocument;
private VideoAdd addVideo;
private AudioAdd addAudio;
private LinkAdd addLink;
private CustomAdd addCustom;
private AiccAdd addAicc;
private ScormAdd addScorm;
private RegistrationCreate createRegistration;
private Utils utils;
private GetVersion getVersion;
public AddRegisterLAs() {
super(System.getProperty("browser"),System.getProperty("browser_version"),System.getProperty("os"),System.getProperty("ov"),System.getProperty("folderName"));
}
#Before
public void setUp() {
login = new Login(driver);
go = new Navigation(driver);
addLa = new LearningActivityAdd(driver);
addImage = new ImageAdd(driver);
addDocument = new DocumentAdd(driver);
addVideo = new VideoAdd(driver);
addAudio = new AudioAdd(driver);
addLink = new LinkAdd(driver);
addCustom = new CustomAdd(driver);
addAicc = new AiccAdd(driver);
addScorm = new ScormAdd(driver);
utils = new Utils();
getVersion = new GetVersion(driver);
createRegistration = new RegistrationCreate(driver);
}
#Test
public void Shallow() throws Exception {
//utils.logAndPrint("AddRegisterLAs");
int maxLAs = 1000;
int maxRegs = 1000;
//-Print to screen to create log. Log can be copied and pasted to Word document or elsewhere as needed.
System.out.println("\n" + "---------------------------------------------------------------------------------"+ "\r\n");
System.out.println("---------------------------------------------------------------------------------"+ "\r\n");
System.out.println("Adding and Registering Learning Activities Automation"+ "\r\n");
System.out.println("---------------------------------------------------------------------------------"+ "\r\n");
System.out.println("---------------------------------------------------------------------------------"+ "\r\n");
//-Load the properties
System.out.println("\n" + "---------------------------------------------------------------------------------"+ "\r\n");
System.out.println("Read in PROPERTIES file"+ "\r\n");
System.out.println("---------------------------------------------------------------------------------"+ "\r\n");
Properties prop = new Properties();
InputStream input = null;
At first kindly check that you have access to that driver path which you mentioned inside if.
Related
In the Extent Report, I want to display the name of test instead of method name.
So I found a solution, added a test name attribute for #Test annotation
Problem 1: In the report I see null being returned for getTestName method.
Problem 2: I am not able to create a test under 'Tests' column in the report with the test name.
Here is the line which does that:
test = extent.createTest(Thread.currentThread().getStackTrace()1.getMethodName().toString());
I have added my test case and the Extent Report code. Please suggest.
/*============================================================================================================================
Test case : Verify if the save button is enabled on giving a comparison name in the save comparison form
======================================================================================*/
#Test(testName ="Verify if the save button is enabled")
public void verifySaveButtonEnabled() {
//test = extent.createTest(Thread.currentThread().getStackTrace()[1].getMethodName());
test = extent.createTest(Thread.currentThread().getStackTrace()[1].getMethodName().toString());
Base.getBrowser();
InvestmentsSearch.login(Base.driver);
InvestmentsSearch.InvestmentsLink(Base.driver).click();
JavascriptExecutor jse = (JavascriptExecutor)Base.driver;
jse.executeScript("window.scrollBy(0,750)", "");
InvestmentsSearch.ViewResults(Base.driver).click();
for(int i=0;i<=2;i++)
{
My code for Extent Report:
package com.gale.precision.FundVisualizer.core;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebElement;
import org.testng.ITestContext;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;
import com.aventstack.extentreports.markuputils.ExtentColor;
import com.aventstack.extentreports.markuputils.MarkupHelper;
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;
import com.aventstack.extentreports.reporter.configuration.ChartLocation;
import com.aventstack.extentreports.reporter.configuration.Theme;
import com.gale.precision.FundVisualizer.utility.SendEmail;
public class ExtentReport {
public static ExtentHtmlReporter htmlReporter;
public static ExtentReports extent;
public static ExtentTest test;
public static String suiteName;
#BeforeSuite
public static void setUp(ITestContext ctx) {
// String currentDate=getDateTime();
suiteName = ctx.getCurrentXmlTest().getSuite().getName();
htmlReporter = new ExtentHtmlReporter(System.getProperty("user.dir") + "/Reports/" + suiteName + ".html");
extent = new ExtentReports();
extent.attachReporter(htmlReporter);
extent.setSystemInfo("OS", "Windows");
extent.setSystemInfo("Host Name", "CI");
extent.setSystemInfo("Environment", "QA");
extent.setSystemInfo("User Name", "QA_User");
htmlReporter.config().setChartVisibilityOnOpen(true);
htmlReporter.config().setDocumentTitle("AutomationTesting Report");
htmlReporter.config().setReportName("testReport");
htmlReporter.config().setTestViewChartLocation(ChartLocation.TOP);
htmlReporter.config().setTheme(Theme.STANDARD);
}
#AfterMethod
public void getResult(ITestResult result) throws IOException {
if (result.getStatus() == ITestResult.FAILURE) {
String screenShotPath = GetScreenShot.capture(Base.driver, "screenShotName", result);
test.log(Status.FAIL, MarkupHelper.createLabel(result.getTestName() + " Test case FAILED due to below issues:",
ExtentColor.RED));
test.fail(result.getThrowable());
test.fail("Snapshot below: " + test.addScreenCaptureFromPath(screenShotPath));
} else if (result.getStatus() == ITestResult.SUCCESS) {
test.log(Status.PASS, MarkupHelper.createLabel(result.getTestName() + " Test Case PASSED", ExtentColor.GREEN));
} else {
test.log(Status.SKIP,
MarkupHelper.createLabel(result.getTestName()+ " Test Case SKIPPED", ExtentColor.ORANGE));
test.skip(result.getThrowable());
}
extent.flush();
}
#AfterSuite
public void tearDown() throws Exception {
System.out.println("In After Suite");
SendEmail.execute(SendEmail.path);
}
public static String getDateTime() {
// Create object of SimpleDateFormat class and decide the format
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
// get current date time with Date()
Date date = new Date();
// Now format the date
String currentDate = dateFormat.format(date);
String newDate = currentDate.replace('/', '_');
String newCurrentDate = newDate.replace(':', '.');
return newCurrentDate;
}
public void elementHighlight(WebElement element) {
for (int i = 0; i < 2; i++) {
JavascriptExecutor js = (JavascriptExecutor) Base.driver;
js.executeScript(
"arguments[0].setAttribute('style', arguments[1]);",
element, "color: red; border: 3px solid red;");
js.executeScript(
"arguments[0].setAttribute('style', arguments[1]);",
element, "");
}
}
}
I want to display test name in the report at the selected area. Please refer the image
Thanks in advance!!
For Problem 1, you should be using result.getMethod().getMethodName() to get the test method name.
For Problem 2, a cleaner way of doing this would be to add a BeforeMethod and initialize the Extent test here instead of initializing it in every test method. You can get the testname or any other annotation value using the below technique inside BeforeMethod:
#BeforeMethod
public void setup(Method method) {
String testMethodName = method.getName(); //This will be:verifySaveButtonEnabled
String descriptiveTestName = method.getAnnotation(Test.class).testName(); //This will be: 'Verify if the save button is enabled'
test = extent.createTest(descriptiveTestName);
}
#Test(descritpion="Verify if the save button is enabled")
you can use
result.getMethod().getDescription()
you have to initialize ITestResult result else you can use these methods in Listeners class
Use the extent.endTest(test); statement correctly as shown below. It worked for me.
//Testng to listen to this extent reports.
public class ExtentReporterNG implements IReporter {
private ExtentReports extent;
public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) {
extent = new ExtentReports(outputDirectory + File.separator + "ExtentReportsTestNG.html", true);
for (ISuite suite : suites) {
Map<String, ISuiteResult> result = suite.getResults();
for (ISuiteResult r : result.values()) {
ITestContext context = r.getTestContext();
buildTestNodes(context.getPassedTests(), LogStatus.PASS);
buildTestNodes(context.getFailedTests(), LogStatus.FAIL);
buildTestNodes(context.getSkippedTests(), LogStatus.SKIP);
}
}
extent.flush();
extent.close();
}
private void buildTestNodes(IResultMap tests, LogStatus status) {
ExtentTest test;
if (tests.size() > 0) {
for (ITestResult result : tests.getAllResults()) {
test = extent.startTest(result.getMethod().getMethodName());
for (String group : result.getMethod().getGroups())
test.assignCategory(group);
String message = "Test " + status.toString().toLowerCase() + "ed";
if (result.getThrowable() != null){
message = result.getThrowable().getMessage();
}else{
test.log(status, message);
extent.endTest(test);
}
test.setStartedTime(getTime(result.getStartMillis()));
test.setEndedTime(getTime(result.getEndMillis()));
}
}
}
private Date getTime(long millis) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(millis);
return calendar.getTime();
}
}
After upgrading to latest selenium, Selenium grid is giving an error for RegistrationRequest(). I am getting req.setRole(), req.setConfiguration(), etc. not found. look like RegistrationRequest() class got change in selenium new version but not sure how to use that class and modify my existing code. Any idea how to resolve this?
Here is my code,
package selenium;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.openqa.grid.common.GridRole;
import org.openqa.grid.common.RegistrationRequest;
import org.openqa.grid.internal.utils.configuration.GridHubConfiguration;
import org.openqa.grid.internal.utils.SelfRegisteringRemote;
import org.openqa.grid.web.Hub;
import org.openqa.selenium.remote.DesiredCapabilities;
public class SeleniumGrid {
private static Hub hub;
private static URL remoteURL;
private static RegistrationRequest req = new RegistrationRequest();
private Map<String, Object> nodeConfig = new HashMap<String, Object>();
private static SelfRegisteringRemote remote = new SelfRegisteringRemote(req);
SeleniumBase sb = new SeleniumBase();
public void setup() throws Exception {
hub = getHub("localhost", 4458);
remoteURL = new URL("http://" + hub.getUrl() + ":" + 5555);
// req = setRegRequest();
req.setRole(GridRole.NODE);
req.addDesiredCapability(sb.getCapability());
List<DesiredCapabilities> dc = req.getCapabilities();
for (DesiredCapabilities c : dc) {
System.out.println("Using capabilities: " + c.toString());
}
// nodeConfig.put(req.AUTO_REGISTER, true);
nodeConfig.put(req.HUB_HOST, hub.getHost());
nodeConfig.put(req.HUB_PORT, hub.getPort());
nodeConfig.put(req.PORT, 5555);
// nodeConfig.put(RegistrationRequest.PROXY_CLASS, "org.openqa.grid.selenium.proxy.DefaultRemoteProxy");
nodeConfig.put(req.MAX_SESSION, 1);
// nodeConfig.put(RegistrationRequest.CLEAN_UP_CYCLE, 2000);
nodeConfig.put(req.REMOTE_HOST, remoteURL);
nodeConfig.put(req.MAX_INSTANCES, 1);
nodeConfig.put(req.BROWSER, "firefox");
nodeConfig.put(req.UNREGISTER_IF_STILL_DOWN_AFTER, 20000);
nodeConfig.put(req.HOST, hub.getHost());
System.out.println("Hub Port: " + hub.getHost() + hub.getPort());
System.out.println(req.HOST);
System.out.println(req.HUB_HOST);
System.out.println(req.HUB_PORT);
req.setConfiguration(nodeConfig);
remote.startRemoteServer();
remote.startRegistrationProcess();
}
public RegistrationRequest setRegRequest() {
RegistrationRequest request = new RegistrationRequest();
request.setRole(GridRole.NODE);
request.addDesiredCapability(sb.getCapability());
List<DesiredCapabilities> dc = request.getCapabilities();
for (DesiredCapabilities c : dc) {
System.out.println("Using capabilities: " + c.toString());
}
return request;
}
public Hub getHub(String host, int port) {
GridHubConfiguration config = new GridHubConfiguration();
config.setHost(host);
config.setPort(port);
Hub someHub = new Hub(config);
return someHub;
}
public void tearDown() throws Exception {
remote.stopRemoteServer();
hub.stop();
}
}
Here's a full fledged working example that starts a hub, starts a node, wires up the node to the hub, runs a test against the locally spun off hub, and then goes on to shut down the node and then the hub.
import org.openqa.grid.common.GridRole;
import org.openqa.grid.internal.utils.SelfRegisteringRemote;
import org.openqa.grid.internal.utils.configuration.GridHubConfiguration;
import org.openqa.grid.internal.utils.configuration.GridNodeConfiguration;
import org.openqa.grid.selenium.proxy.DefaultRemoteProxy;
import org.openqa.grid.web.Hub;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.remote.server.SeleniumServer;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.net.MalformedURLException;
import java.net.URL;
public class SeleniumGrid {
private Hub hub;
private SelfRegisteringRemote remote;
#BeforeClass
public void setup() throws Exception {
hub = getHub("localhost", 4458);
hub.start();
remote = new SelfRegisteringRemote(getNodeConfiguration());
remote.addBrowser(DesiredCapabilities.firefox(), 2);
SeleniumServer server = new SeleniumServer(remote.getConfiguration());
remote.setRemoteServer(server);
remote.startRemoteServer();
remote.startRegistrationProcess();
}
#Test
public void test() throws MalformedURLException {
URL url = new URL(hub.getUrl() + "/wd/hub");
RemoteWebDriver driver = new RemoteWebDriver(url, DesiredCapabilities.firefox());
try {
driver.get("http://www.google.com");
System.err.println("Title " + driver.getTitle());
} finally {
driver.quit();
}
}
#AfterClass
public void tearDown() throws Exception {
remote.stopRemoteServer();
hub.stop();
}
private GridNodeConfiguration getNodeConfiguration() {
GridNodeConfiguration nodeConfiguration = new GridNodeConfiguration();
nodeConfiguration.register = true;
nodeConfiguration.hub = String.format("http://%s:%d", hub.getConfiguration().host, hub.getConfiguration().port);
nodeConfiguration.port = 5555;
nodeConfiguration.proxy = DefaultRemoteProxy.class.getCanonicalName();
nodeConfiguration.maxSession = 1;
nodeConfiguration.cleanUpCycle = 2000;
nodeConfiguration.unregisterIfStillDownAfter = 20000;
nodeConfiguration.role = GridRole.NODE.toString();
nodeConfiguration.port = 5555;
nodeConfiguration.getHubHost();
nodeConfiguration.hub = String.format("http://%s:%d", hub.getConfiguration().host, hub.getConfiguration().port);
return nodeConfiguration;
}
private Hub getHub(String host, int port) {
GridHubConfiguration config = new GridHubConfiguration();
config.host = host;
config.port = port;
return new Hub(config);
}
}
I am using factory with data provider reading my data from an excel sheet. The issue is that my tests are passing when the last row from the excel sheet is provided through data providers. Preceding rows are giving me NPE.
I am pasting my code here. Thanks for taking a look.
Here is my factory class:
//Factory test class
public class testFactory {
#Factory(dataProviderClass=dataProvider.MyDataProvider.class,dataProvider="userDataProvider")
public Object[] factoryMethod(String email,String password,String firstName, String lastName) {
TestFaceBookUsingExcelSheetAsDataProvider instance = new TestFaceBookUsingExcelSheetAsDataProvider(email,password,firstName, lastName);
return new Object[] { instance };
}
}
This is my data provider class
//Data Provider class
public class MyDataProvider {
#DataProvider(name = "userDataProvider")
public static Object[][] getUserData() {
return ExcelUtils.fileDataProvider("user");//TODO: currently this value is not in use, hard coded in method
}
}
Here is the method which my data provider class method is calling to read data from excel sheet
//Utility Class's helper method to read test data from excel sheet
//#DataProvider(name = "fileDataProvider")
public static Object[][] fileDataProvider(String sheetName) { //TODO: sheetname
try {
//ExcelUtils.setExcelFile(Constant.Path_TestData + Constant.File_TestData,"user");
System.out.println(Constant.Path_TestData + Constant.File_TestData); //TODO
//XSSFWorkbook workbook = new XSSFWorkbook(Constant.Path_TestData + Constant.File_TestData);
XSSFWorkbook workbook = new XSSFWorkbook("<path_to_file>\\TestData.xlsx");
XSSFSheet sheet = workbook.getSheet("user");
Iterator<Row> rowIterator = sheet.iterator();
ArrayList<ArrayList<String>> rowdata = new ArrayList<ArrayList<String>>();
boolean isHeader = true;
while (rowIterator.hasNext()) {
ArrayList<String> columndata = new ArrayList<String>();
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
if (row.getRowNum() > 0) { // To filter column headings
isHeader = false;
if(cell.getCellType() == org.apache.poi.ss.usermodel.Cell.CELL_TYPE_NUMERIC) {
columndata.add(cell.getNumericCellValue() + "");
} else if (cell.getCellType() == org.apache.poi.ss.usermodel.Cell.CELL_TYPE_STRING) {
columndata.add(cell.getStringCellValue());
} else if (cell.getCellType() == org.apache.poi.ss.usermodel.Cell.CELL_TYPE_BOOLEAN) {
columndata.add(cell.getBooleanCellValue() + "");
}
}
}
if (isHeader == false ) {
rowdata.add(columndata); // to make sure we don't add an empty array for header row
}
}
workbook.close();
String[][] return_array = new String[rowdata.size()][];
for (int i = 0; i < rowdata.size(); i++) {
ArrayList<String> row = rowdata.get(i);
return_array[i] = row.toArray(new String[row.size()]);
}
return return_array;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
And this, finally, is my test code
//My testclass
package test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import pgFactory.fb.HomePage;
import pgFactory.fb.LandingPage;
import pgFactory.fb.TimeLine;
public class TestFaceBookUsingExcelSheetAsDataProvider {
// Constructor to be called from factory class
public TestFaceBookUsingExcelSheetAsDataProvider(String email, String password, String firstName, String lastName) {
this.email = email;
this.password = password;
this.firstName = firstName;
this.lastName = lastName;
}
// class variables to be used in the tests
WebDriver driver;
LandingPage lp;
HomePage hp;
TimeLine tl;
// Variables from data provider which in turn is reading from excel sheet
private String email = null;
private String password = null;
private String firstName = null;
private String lastName = null;
#Override
public String toString()
{
return this.email+ " " + this.password + " " + this.firstName + " " + this.lastName;
}
#BeforeTest
public void setup() {
// Driver
driver = new FirefoxDriver();
// Pages
lp = new LandingPage(driver).get();
hp = new HomePage(driver).get();
tl = new TimeLine(driver).get();
}
// Test methods
#Test()
public void testLogin() {
lp.login(email, password);
// Assert that after login you will see your home page
Assert.assertEquals(hp.getUserLeftNavName().getAttribute("innerHTML"), firstName + " " + lastName,
"The full name is not correct on the left side user navigation frame");
Assert.assertEquals(hp.getUserUpperNavName().getAttribute("innerHTML"), firstName,
"The first is not correct on the upper user navigation bar");
hp.logOut();
}
#Test
public void testMyPage() {
lp.login(email, password);
hp.getUserLeftNavName().click();
String name = (new WebDriverWait(driver, 5))
.until(ExpectedConditions.presenceOfElementLocated(By.id("fb-timeline-cover-name"))).getText();
Assert.assertEquals(name, firstName + " " + lastName, "The fullname on timeline cover is not correct");
hp.logOut();
}
#AfterTest
public void teardown() {
driver.quit();
}
}
BTW, I am learning selenium by automating a few tests on facebook page. So, if I am making a silly mistake, please be patient with me.
I found the solution by debugging the code. The issue is when factory is used then I don't have any control over the BeforeTest annotated methods. These are not being run before tests start to execute. So, NPE is thrown because my pageObject is not instantiated yet.
Workaround. I annotated setup method with #Test and made other tests dependent on this test and it worked like a charm. Its not the best solution because now I have to make every existing and future tests with this dependsOnMethods parameter in annotation.
If you know of a better solution, please reply.
I get a error message below .. when I run the code for hitting google Calendar API.There is a client_secrets.json file that has the credentials (client ID and redirectID) . I unzipped and ran the package google gave, it successfully runs and I could see that by a "Success,Add code here"message. after which it throws me a nullpointer exception for which I'm not sure what has gone wrong.please help. Downloaded the sample project from here https://developers.google.com/api-client-library/java/apis/calendar/v3
May 01, 2014 12:59:42 PM com.google.api.client.util.store.FileDataStoreFactory setPermissionsToOwnerOnly
WARNING: unable to change permissions for everybody: C:\Users\Aishwarya Anand\.store\calendar_sample
May 01, 2014 12:59:42 PM com.google.api.client.util.store.FileDataStoreFactory setPermissionsToOwnerOnly
WARNING: unable to change permissions for owner: C:\Users\Aishwarya Anand\.store\calendar_sample
Success! Now add code here.
inserting event ...
Aish Event from the new Google API
2014-05-01T16:59:42.545Z
2014-05-01T17:59:42.545Z
java.lang.NullPointerException
at com.google.api.client.repackaged.com.google.common.base.Preconditions.checkNotNull(Preconditions.java:191)
at com.google.api.client.util.Preconditions.checkNotNull(Preconditions.java:127)
at com.google.api.client.json.jackson2.JacksonFactory.createJsonParser(JacksonFactory.java:96)
at com.google.api.client.json.JsonObjectParser.parseAndClose(JsonObjectParser.java:85)
at com.google.api.client.json.JsonObjectParser.parseAndClose(JsonObjectParser.java:81)
at com.google.api.client.auth.oauth2.TokenResponseException.from(TokenResponseException.java:88)
at com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:287)
at com.google.api.client.auth.oauth2.TokenRequest.execute(TokenRequest.java:307)
at com.google.api.client.auth.oauth2.Credential.executeRefreshToken(Credential.java:570)
at com.google.api.client.auth.oauth2.Credential.refreshToken(Credential.java:489)
at com.google.api.client.auth.oauth2.Credential.intercept(Credential.java:217)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:859)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:410)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:343)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:460)
at com.google.api.services.samples.calendar.cmdline.CalendarSample.insertEventTest(CalendarSample.java:170)
at com.google.api.services.samples.calendar.cmdline.CalendarSample.main(CalendarSample.java:116)
Class here,
package com.google.api.services.samples.calendar.cmdline;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.DateTime;
import com.google.api.client.util.store.DataStoreFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.calendar.Calendar;
import com.google.api.services.calendar.CalendarScopes;
import com.google.api.services.calendar.model.*;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Date;
import java.util.TimeZone;
public class CalendarSample {
/**
* Be sure to specify the name of your application. If the application name is {#code null} or
* blank, the application will log a warning. Suggested format is "MyCompany-ProductName/1.0".
*/
private static final String APPLICATION_NAME = "Caritas-CalendarAPI/1.0";
/** Directory to store user credentials. */
private static final java.io.File DATA_STORE_DIR =
new java.io.File(System.getProperty("user.home"), ".store/calendar_sample");
/**
* Global instance of the {#link DataStoreFactory}. The best practice is to make it a single
* globally shared instance across your application.
*/
private static FileDataStoreFactory dataStoreFactory;
/** Global instance of the JSON factory. */
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
/** Global instance of the HTTP transport. */
private static HttpTransport httpTransport;
#SuppressWarnings("unused")
private static Calendar client;
/** Authorizes the installed application to access user's protected data. */
private static Credential authorize() throws Exception {
// load client secrets
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
new InputStreamReader(CalendarSample.class.getResourceAsStream("/client_secrets.json")));
// Set up authorization code flow.
// Ask for only the permissions you need. Asking for more permissions will
// reduce the number of users who finish the process for giving you access
// to their accounts. It will also increase the amount of effort you will
// have to spend explaining to users what you are doing with their data.
// Here we are listing all of the available scopes. You should remove scopes
// that you are not actually using.
Set<String> scopes = new HashSet<String>();
scopes.add(CalendarScopes.CALENDAR);
scopes.add(CalendarScopes.CALENDAR_READONLY);
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
httpTransport, JSON_FACTORY, clientSecrets, scopes)
.setDataStoreFactory(dataStoreFactory)
.build();
// authorize
return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}
public static void main(String[] args) {
try {
// initialize the transport
httpTransport = GoogleNetHttpTransport.newTrustedTransport();
// initialize the data store factory
dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);
// authorization
Credential credential = authorize();
// set up global Calendar instance
client = new Calendar.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME).build();
System.out.println("Success! Now add code here.");
insertEventTest();
//getEventList();
//getEventTest();
//sertEventTest();
} catch (IOException e) {
System.err.println(e.getMessage());
} catch (Throwable t) {
t.printStackTrace();
}
System.exit(1);
}
private static void getEventList() throws IOException {
String pageToken = null;
do {
Events events = client.events().list("primary").setPageToken(pageToken).execute();
List<Event> items = events.getItems();
for (Event event : items) {
System.out.println(" id: " + event.getId() + "; summary: " + event.getSummary());
}
pageToken = events.getNextPageToken();
} while (pageToken != null);
}
private static void getEventTest() throws IOException {
String eventId = "idkoi3c55lvegs2ev333u28grk5c";
Event event = client.events().get("primary", eventId).execute();
System.out.println(event.getSummary());
}
private static void insertEventTest() throws IOException {
System.out.println("inserting event ...");
Event event = new Event();
event.setSummary("Aish Event from the new Google API");
event.setLocation("Somewhere");
System.out.println(event.getSummary());
Date startDate = new Date();
Date endDate = new Date(startDate.getTime() + 3600000);
DateTime start = new DateTime(startDate, TimeZone.getTimeZone("UTC"));
event.setStart(new EventDateTime().setDateTime(start));
System.out.println(start.toStringRfc3339());
DateTime end = new DateTime(endDate, TimeZone.getTimeZone("UTC"));
event.setEnd(new EventDateTime().setDateTime(end));
System.out.println(end.toStringRfc3339());
Event createdEvent = client.events().insert("primary", event).execute();
System.out.println("event id" + createdEvent.getId());
}
}
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;
}
}