Get OS system and relative path to a folder in java - java

I write my test on my local Windows, and I create webdriver like this:
#BeforeMethod
#Parameters("browser")
public void setUp(String browser) throws Exception {
if (browser.equalsIgnoreCase("chrome")) {
System.out.println("Chrome test starting ...");
System.setProperty("webdriver.chrome.driver", "src/test/resources/drivers/chromedriver_win.exe");
webDriver = new ChromeDriver();
}
else {
throw new Exception("Browser is not supported");
}
For the setProperty, I use a hard path to Chrome Driver, but I would like change the path to relative by checking the OS to use appropriate driver for Windows and Mac. Can someone give me a hint. Thanks

By using config property file you can get both browser type and chrome driver location.
you can create one folder in your work space with the name Drivers and paste your chrome driver
Below is config.properties file
browserType=Chrome
ChromeDriver = Drivers/chromedriver.exe
Below is the code to run chrome driver on different operating systems
String os = System.getProperty("os.name");
public String currentBrowser;
if(CONFIG.getProperty("browserType").contains(","))
{
data=currentBrowser;
}
if (os.contains("Windows"))
{
else if (data.equals("Chrome")) {
APP_LOGS.debug("Chrome Browser Opening Method Start");
DesiredCapabilities capability = DesiredCapabilities.chrome();
// To Accept SSL certificate
capability.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
System.setProperty("webdriver.chrome.driver",
CONFIG.getProperty("ChromeDriver"));
Thread.sleep(10000);
driver = new ChromeDriver();
driver.manage().window().maximize();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
long
implicitWaitTime=Long.parseLong(CONFIG.getProperty("implicitwait"));
driver.manage().timeouts().implicitlyWait(implicitWaitTime,
TimeUnit.SECONDS);
driver.manage().window().maximize();
}
return os;
}

Why are you putting chromedriver in src? Your jar will be needing that folders while running.
Source Code and the Binary files should not be put together in production environment.
Create a libs folder and put all types of chromedrivers in it. With slight change in name.
chromedriver_mac
chromedriver_win
chromedriver_linux
Code
#BeforeMethod
#Parameters("browser")
public void setUp(String browser) throws Exception {
if (browser.equalsIgnoreCase("chrome")) {
System.out.println("Chrome test starting ...");
System.setProperty("webdriver.chrome.driver", getChromeDriverPath());
webDriver = new ChromeDriver();
}
else {
throw new Exception("Browser is not supported");
}
}
public static String getChromeDriverPath() {
String OS = System.getProperty("os.name");
if (OS.contains("Window")) {
return "libs/chromedriver_win"
} else if (OS.contains("Mac")) {
return "libs/chromedriver_mac"
} else {
return "libs/chromedriver_linux"
}
}

The below code should work,
if(type.equalsIgnoreCase("CHROME"))
{
log.info("Executing Operating System = "+System.getProperty("os.name").toLowerCase());
String osname =System.getProperty("os.name");
if(osname.toLowerCase().contains("windows")) System.setProperty("webdriver.chrome.driver","src/test/resources/chromedriver.exe" );
else if(osname.toLowerCase().contains("linux"))
{
String filepathtoset = System.getProperty("user.dir")+"/src/test/resources/chromedriver";
System.setProperty("webdriver.chrome.driver",filepathtoset );
}
else System.setProperty("webdriver.chrome.driver","src/test/resources/chromedrivermac");

Related

Running Selenium on jenkins takes my local chromedriver

I'm trying to test our website with selenium via Jenkins so that everyday every feature gets tested.
The problem is that Jenkins fails because he is trying to get the chromedriver with my local path but there is no local path.
The error message:
[ERROR] main(at.s2gplus.selenium.TestPromoteToAdmin) Time elapsed:
0.006 s <<< FAILURE! java.lang.IllegalStateException: The driver executable does not exist:
/opt/jenkins/workspace/buzzApi/C:/Users/mario/AppData/Local/Google/Chrome/Application/chromedriver.exe
at
at.s2gplus.selenium.TestPromoteToAdmin.main(TestPromoteToAdmin.java:36)
The code:
public class TestPromoteToAdmin {
WebDriver driver = new ChromeDriver();
#Test
public void main() {
driver.get("https://192.168.1.45:8080/");
WebDriverWait wait = new WebDriverWait(driver, 90);
driver.manage().window().maximize();
driver.findElement(By.id("details-button")).click();
driver.findElement(By.id("proceed-link")).click();
driver.findElement(By.id("home-open-sign-in")).click();
driver.findElement(By.id("login-username")).sendKeys("tester");
driver.findElement(By.id("login-password")).sendKeys("wurst01");
driver.findElement(By.id("login-action")).click();
wait.until(ExpectedConditions.elementToBeClickable(By.id("left-menu-room-title-add-action"))).click();
driver.findElement(By.id("create-room-name-input")).sendKeys("Selenium Admin test");
driver.findElement(By.id("create-room-description-input")).sendKeys("Selenium Test");
driver.findElement(By.id("create-room-save")).click();
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement roomToClick = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//span[contains(text(), 'Selenium Admin test')]")));
js.executeScript("arguments[0].scrollIntoView();", roomToClick);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
wait.until(ExpectedConditions.elementToBeClickable(roomToClick)).click();
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//span[contains(#id, 'left-roomlist-settingsicon')]"))).click();
WebElement addMemberBtn = wait.until(ExpectedConditions.elementToBeClickable(By.id("room-settings-add-user")));
addMemberBtn.click();
WebElement checkBox = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("label[for='990bd6a8-62af-48c5-89a5-33019483c91f'")));//("cb732433-eae9-434b-96da-b4d5a499208c"));
checkBox.click();
WebElement addBtn = driver.findElement(By.id("room-settings-add-button"));
addBtn.click();
WebElement saveUserBtn = driver.findElement(By.id("room-settings-save"));
saveUserBtn.click();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//span[contains(#id, 'left-roomlist-settingsicon')]"))).click();
wait.until(ExpectedConditions.elementToBeClickable(By.id("general-menu-list-item-settings"))).click();
wait.until(ExpectedConditions.elementToBeClickable(By.id("room-settings-context-change-role-to-moderator"))).click();
wait.until(ExpectedConditions.elementToBeClickable(By.id("general-menu-list-item-settings"))).click();
wait.until(ExpectedConditions.elementToBeClickable(By.id("room-settings-context-change-role-to-admin"))).click();
driver.findElement(By.id("room-settings-save")).click();
driver.findElement(By.id("top-logout")).click();
driver.findElement(By.id("home-open-sign-in")).click();
driver.findElement(By.id("login-username")).sendKeys("tester01");
driver.findElement(By.id("login-password")).sendKeys("wurst02");
driver.findElement(By.id("login-action")).click();
roomToClick = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//span[contains(text(), 'Selenium Admin test')]")));
js.executeScript("arguments[0].scrollIntoView();", roomToClick);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
wait.until(ExpectedConditions.elementToBeClickable(roomToClick)).click();
WebElement roomAdmin = driver.findElement(By.xpath("//span[contains(text(), 'Selenium Admin test')]"));
String room = roomAdmin.getText();
assertTrue(room, true);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//span[contains(#id, 'left-roomlist-settingsicon')]"))).click();
wait.until(ExpectedConditions.elementToBeClickable(By.id("meeting-settings-open-close-room-modal"))).click();
wait.until(ExpectedConditions.elementToBeClickable(By.id("meeting-settings-close-room-confirm"))).click();
}
#BeforeTest
public void beforeTest() {
ChromeOptions options = new ChromeOptions();
options.setHeadless(true);
options.setAcceptInsecureCerts(true);
driver = new ChromeDriver(options);
}
#AfterTest
public void afterTest() {
driver.quit();
}
}
line 36 is above driver.get("https://192.168.1.45:8080/"); but I have deleted it a long time ago
Install Selenium Grid Plugin in the Jenkins, use below code for node setup. Update the versions of selenium server standalone jar and browser versions in the below code.
java -jar selenium-server-standalone-x.xx.x.jar -
Dwebdriver.chrome.driver="C:\yourpath\chromedriver.exe" -role node -hub
http://localhost:4444/grid/register -browser "browserName=internet
explorer,version=xx,platform=WINDOWS" -browser
"browserName=chrome,version=xx,platform=WINDOWS"
Please update below line of code for starting
WebDriver driver = null;
#Test
public void main() {
System.setProperty("webdriver.chrome.driver","E:\\drivers\\ChromeDrivers\\85\\chromedriver.exe");
driver = new ChromeDriver();
driver.get("https://192.168.1.45:8080/");
WebDriverWait wait = new WebDriverWait(driver, 90);
driver.manage().window().maximize(); ```

Can we use Selenium or any other jars to get network response and validate

I have a requirement here that I need to verify the network response values using selenium & java.
It would be great if there is any code that could help me out.
The action that I want to perform (which is needed to be automated) is
load the application https://www.ancestry.com
press F12 and go to network tab when application is loading
select a respective network containing b/ss
click on it and get the values in the query parameters
I have highlighted them in the below image
Note: I need to perform this action for every click event that happen after the application is loaded.
Is this possible in selenium
This is the code that I tried to get the values recorded am I doing it right please help
public static void main(String[] args) throws IOException {
System.setProperty("webdriver.chrome.driver",
new File(".").getCanonicalPath() + "\\WebDriver\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.ancestry.com");
//capture(driver);
driver.quit();
}
public static void capture(WebDriver driver) throws IOException {
OutputStream logfile = new FileOutputStream(new File(new
File(".").getCanonicalPath() + "\\log.txt"), true);
PrintStream printlog = new PrintStream(logfile);
LogEntries logs = driver.manage().logs().get(LogType.PERFORMANCE);
for (LogEntry entry : logs) {
if (entry.toString().contains("\"type\":\"Img\""))
System.out.println(entry.toString());
printlog.append(new Date(entry.getTimestamp()) + " " + entry.toString() + " "
+ System.getProperty("line.separator"));
printlog.append(System.getProperty("line.separator"));
printlog.append(System.getProperty("line.separator"));
}
printlog.close();
}
We can get all the network logs using browser mob proxy
private static BrowserMobProxy proxy = new BrowserMobProxyServer();
public webLib(String browser) {
logReport.logMethodStart("Launch Application");
Proxy seleniumProxy = null;
proxy.start();
seleniumProxy = ClientUtil.createSeleniumProxy(proxy);
if (browser.equalsIgnoreCase("chrome")) {
try {
System.setProperty("webdriver.chrome.driver",
new File(".").getCanonicalFile() + seperator + "WebDriver" + seperator + "chromeDriver.exe");
} catch (IOException e) {
e.printStackTrace();
}
ChromeOptions options = new ChromeOptions();
options.setCapability(CapabilityType.PROXY, seleniumProxy);
options.setAcceptInsecureCerts(true);
options.addArguments("--ignore-certificate-errors");
options.addArguments("--disable-popup-blocking");
options.addArguments("--no-sandbox");
options.addArguments("--no-sandbox");
driver = new ChromeDriver(options);
} else if (browser.equalsIgnoreCase("firefox")) {
}
driver.manage().deleteAllCookies();
driver.manage().window().maximize();
driver.manage().timeouts().pageLoadTimeout(20, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
if (driver != null) {
logReport.logStep(Status.PASS, "Browser launched successfully", driver);
}
}
You can reffer the following site
https://www.swtestacademy.com/webdriver-browsermob-proxy/

Remote run selenium test cases for download file test using chrome

I have a test which I need to run on a remote machine using selenium /chrome/ java. When I run same test cases on local it works fine there is no error or anything it pass. when I run same test cases on remote machine after click on download file test freezer up or will keep counting there is no error or anything.
//Click on download file icon
click(driver, downloadIcon, format + " icon " + summaryReportName);
// after click test freezer or will count keep i++
try {
// file location on network path location same same local run and remote run
long beforeCount = Files.list(Paths.get("//ap-521-6be1/Selenium/Onetest/excelfiles")).count();
System.out.println(beforeCount);
long afterCount = beforeCount;
int i = 1;
while (beforeCount >= afterCount) {
Thread.sleep(1000);
afterCount = Files.list(Paths.get("//ap-521-6be1/Selenium/Onetest/excelfiles")).count();
// will continue printing the count i++ without any error
//System.out.println(i++);
i++;
}
System.out.println("Time took to download report:" +i+" seconds");
} catch (IOException e) {
Add_Log.info("Excel report not downloaded for Exception");
e.printStackTrace();
}
Thread.sleep(6000);
File theNewestFile = null;
File dir1 = new File("//ap-521-6be1/Selenium/Onetest/excelfiles");
File[] files = dir1.listFiles();
if (files == null || files.length == 0) {
return;
}
File lastModifiedFile = files[0];
String filename1 = lastModifiedFile.getName();
System.out.println(filename1+ " & " + summaryReportName);
if (filename1.contains(summaryReportName)) {
Add_Log.info("Successfully downloaded ");
Reporter.log("Successfully downloaded ");
} else {
Add_Log.info(" not downloaded");
Reporter.log(" not downloaded");
Assert.fail();
}
code for Suite base for test to run on local and remote machine
//To Load Chrome driver Instance.
/*System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+"\\src\\main\\resources\\browserdrivers\\chromedriver.exe");
// String downloadFilepath = System.getProperty("user.dir")+"\\src\\main\\resources\\excelfiles\\";
String downloadFilepath ="//ap-521-6be1/Selenium/Onetest/excelfiles";
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("profile.default_content_settings.popups", 0);
chromePrefs.put("download.default_directory", downloadFilepath);
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", chromePrefs);
options.addArguments("--start-maximized");
options.setExperimentalOption("useAutomationExtension", false);
options.addArguments("disable-infobars");
DesiredCapabilities cap = DesiredCapabilities.chrome();
cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
cap.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.ACCEPT);
cap.setCapability(ChromeOptions.CAPABILITY, options);
driver.set(new ChromeDriver(cap));
Add_Log.info("Chrome Driver Instance loaded successfully.");
*/
//for remote run
DesiredCapabilities capability = DesiredCapabilities.chrome();
ChromeOptions options = new ChromeOptions();
System.setProperty("webdriver.chrome.driver", ("user.dir")+"\\src\\main\\resources\\browserdrivers\\chromedriver.exe");
String downloadFilepath ="//ap-521-6be1/Selenium/Onetest/excelfiles";
options.setExperimentalOption("useAutomationExtension", false);
// driver = new ChromeDriver(options);
// ChromeOptions options = new ChromeOptions();
options.addArguments("--test-type");
options.addArguments("disable-infobars");
options.addArguments("--start-maximized");
options.setExperimentalOption("useAutomationExtension", false);
capability.setBrowserName("chrome");
capability.setPlatform(Platform.WINDOWS);
capability.setCapability(ChromeOptions.CAPABILITY, options);
try {
driver.set(new RemoteWebDriver(new URL("http://146.76.184.178:4455/wd/hub"), capability));
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//For Remote run end
Add_Log.info("Chrome Driver Instance loaded successfully.");
Instead of setting lots of caps and args you can set up manually in Chrome to automatically download files. Following with loading existing browser profile. However I didn't try remotely.
package packageName;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class WebdriverSetup {
public static String chromedriverPath = "C:\\Users\\pburgr\\Desktop\\selenium-tests\\GCH_driver\\chromedriver.exe";
// my default profile folder
public static String chromeProfilePath = "C:\\Users\\pburgr\\AppData\\Local\\Google\\Chrome\\User Data";
public static WebDriver driver;
public static WebDriver startChromeWithCustomProfile() {
System.setProperty("webdriver.chrome.driver", chromedriverPath);
ChromeOptions options = new ChromeOptions();
// loading Chrome with my existing profile instead of a temporary profile
options.addArguments("user-data-dir=" + chromeProfilePath);
driver = new ChromeDriver(options);
driver.manage().window().maximize();
return driver;
}
public static void shutdownChrome() {
driver.close();
driver.quit();
}
}

I've installed Gecko driver but still getting an error

I've installed the Gecko driver because i was getting this error : "java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.gecko.driver system property;"
But after applying the code still i'm getting error for Gecko driver.
Below is my complete code. please let me know what I'm missing.
public class Pawan {
public static WebDriver driver;
public static void main(String[] args){
System.setProperty("webdriver.firefox.marionette","C:\\Users\\Lalit-pc\\Desktop\\geckodriver-v0.21.0-win64\\geckodriver.exe");
driver = new FirefoxDriver();
}
#Test
public void test() {
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("https://www.google.com/");
driver.findElement(By.linkText("Find a Physician")).click();
driver.findElement(By.id("searchZip")).sendKeys("32806");
driver.findElement(By.linkText("Mile Radius")).click();
try{
Thread.sleep(6000);
}catch (InterruptedException ie1) {
ie1.printStackTrace();
}
driver.findElement(By.linkText("20")).click();
driver.findElement(By.linkText("Specialty")).click();
try{
Thread.sleep(6000);
}catch (InterruptedException ie1) {
ie1.printStackTrace();
}
driver.findElement(By.linkText("Anesthesiology")).click();
driver.findElement(By.cssSelector("input[type='submit'][value='Search Now']")).click();
String str= driver.findElement(By.xpath(".//*[#id='finderListView']/div[3]/div[1]/div/div[1]/p")).getText();
if("Anesthesiology".equals(str))
System.out.println("Physician Search Successful");
else
System.out.println("Physician Search NOT Successful");
driver.findElement(By.linkText("Browse Locations")).click();
try{
Thread.sleep(6000);
}catch (InterruptedException ie1) {
ie1.printStackTrace();
}
driver.findElement(By.xpath(".//*[#id='sidebarMenu']/div[1]/form/div/input")).sendKeys("32806");
driver.findElement(By.xpath(".//*[#id='sidebarMenu']/div[1]/form/input")).click();
try{
Thread.sleep(6000);
}catch (InterruptedException ie1) {
ie1.printStackTrace();
}
driver.findElement(By.xpath(".//*[#id='sidebarMenu']/div[2]/section/div/ul/li[1]/a")).click();
try{
Thread.sleep(6000);
}catch (InterruptedException ie1) {
ie1.printStackTrace();
}
WebElement divElement = driver.findElement(By.xpath(".//*[#id='overflow-autoScroll']/li[1]/ul/li/a/div[2]/span[3]"));
String stri = divElement.getText();
if(stri.contains("32806"))
System.out.println("Location Search successful");
else
System.out.println("Location Search not successful");
driver.findElement(By.xpath("html/body/header/div[1]/div[2]/a[3]")).click();
driver.findElement(By.linkText("Health Topics")).click();
try{
Thread.sleep(6000);
}catch (InterruptedException ie1) {
ie1.printStackTrace();
}
driver.findElement(By.linkText("Diabetes")).click();
WebElement divElementtwo = driver.findElement(By.xpath("html/body/div[4]/div/div[1]/div[1]/h2"));
String strn = divElementtwo.getText();
if(strn.contains("Diabetes"))
System.out.println("Blog Search successful");
else
System.out.println("Blog Search not successful");
}
}
To verify gecko driver is compatible with your current firefox & selenium version, do the following:
Keep downloaded gecko driver at System32 if you are on Windows OS & /usr/local/bin if you are on Mac OSX
Run the Selenium Standalone server by this command: java -jar selenium-server-standalone-3.13.0.jar
Open this url in Firefox browser: http://localhost:4444/wd/hub
Create Session and Select Firefox browser
If browser starts then there is no issue with the compatibility of geckodriver with Firefox & Selenium version.
small setup change requied: (latest firefox browser)
public class Pawan {
public static WebDriver driver;
#BeforeClass
public static setup() {
System.setProperty("webdriver.gecko.driver","C:\\Users\\Lalit-pc\\Desktop\\geckodriver-v0.21.0-win64\\geckodriver.exe");
driver = new FirefoxDriver();
}
// Urs test here
JUnit uses a different main entry point than the public static void main(String[] args) method you've defined there, so if you execute the tests, System#setProperty won't be executed.
To add the system property once for all tests in the class, you need to define a #BeforeClass method:
public class Pawan {
public static WebDriver driver;
#BeforeClass
static void init() {
System.setProperty("webdriver.firefox.marionette","C:\\Users\\Lalit-pc\\Desktop\\geckodriver-v0.21.0-win64\\geckodriver.exe");
}
//test cases here...
}
Now, for development purposes, I recommend setting this variable as a constant accessible by your PATH environment variable (OS dependent) rather than setting it as a system property.
You can also define geckodriver in #Test if you do not want #BeforeClass annotation :
#Test
public void test() {
System.setProperty("webdriver.firefox.marionette","C:\\Users\\Lalit-pc\\Desktop\\geckodriver-v0.21.0-win64\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("https://www.google.com/");
This will also work:)

Selenium webdriver : Multiple drivers

I have used 3 drivers firefox, chrome and IE for automated testing.
static WebDriver driver ;
public static void main(String args[]) {
try {
driver = new FirefoxDriver();
runTest(driver, "FireFox");
//Chrome
System.setProperty("webdriver.chrome.driver","E:/selinium_drivers/chromedriver.exe");
driver = new ChromeDriver();
runTest(driver, "Chrome");
//IE
System.setProperty("webdriver.ie.driver","E:/selinium_drivers/IEDriverServer.exe");
driver = new InternetExplorerDriver();
runTest(driver, "IE");
}
The problem is the second driver is starting before the first driver complete it's process. How can i stop second driver till the first driver finish it work.
public static void runTest(WebDriver driver, String browserName) {
try {
testLogin(driver);
testSignupC(driver);
testSignUpCLogin(driver);
driver.close();
} catch(Exception ex) {
//log stack trace
//Alter(test failed in browser name)
}
}
You didn't mention your WebDriver version; my comments are based on API 2.45.
First, you should call driver.quit() instead of close():
/**
* Close the current window, quitting the browser if it's the last window currently open.
*/
void close();
/**
* Quits this driver, closing every associated window.
*/
void quit();
Second, you should secure the driver shutdown in a finally block:
try {
testLogin(driver);
testSignupC(driver);
testSignUpCLogin(driver);
} catch(Exception ex) {
//log stack trace
//Alter(test failed in browser name)
} finally {
driver.quit();
}
Additionally, I would surround quit() with a try/catch on WebDriverException and set driver to null in order to prevent its reuse since the driver initialization (startClient(), startSession()...) is done in the constructor:
} finally {
try {
driver.quit();
catch (WebDriverException e) {
// log if useful else NO OP
}
driver = null;
}

Categories