When I run tests on my local machine it's working but the remote machine is not maximized chrome. Because of this driver cant find the elements on the screen, all tests failed. I have tried all recommended solutions. Here is my code.
public class BrowserFactory extends BaseTest {
public WebDriver prepareDriver() {
WebDriver driver;
if (getAveaConfiguration().isRemote().booleanValue()) {
driver = getRemoteDriver();
//driver.manage().window().maximize();
Dimension d = new Dimension(1936,1056);
driver.manage().window().setSize(d);
System.out.println("PageSize:" + driver.manage().window().getSize());
} else {
driver = getLocalDriver();
driver.manage().window().maximize();
System.out.println(driver.manage().window().getSize());
}
return driver;
}
private WebDriver getRemoteDriver() {
WebDriver webDriver;
DesiredCapabilities cap = getRemoteCapabilities();
try {
System.out.println(getAveaConfiguration().getGridURL());
webDriver = new RemoteWebDriver(new URL(getAveaConfiguration().getGridURL()), cap);
((RemoteWebDriver) webDriver).setFileDetector(new LocalFileDetector());
} catch (MalformedURLException mue) {
throw new TestException(mue);
}
return webDriver;
}
private DesiredCapabilities getRemoteCapabilities() {
DesiredCapabilities capabilities;
if ("firefox".equals(getAveaConfiguration().getBrowser())) {
capabilities = DesiredCapabilities.firefox();
FirefoxProfile profile = new FirefoxProfile();
profile.setAcceptUntrustedCertificates(true);
profile.setAssumeUntrustedCertificateIssuer(false);
profile.setPreference("browser.privatebrowsing.autostart", true);
profile.setPreference("network.proxy.type", 0);
capabilities.setCapability(FirefoxDriver.PROFILE, profile);
return capabilities;
} else if ("ie".equals(getAveaConfiguration().getBrowser())) {
return DesiredCapabilities.internetExplorer();
} else {
capabilities = DesiredCapabilities.chrome();
ChromeOptions options = new ChromeOptions();
Map<String, Object> prefs = new HashMap<>();
prefs.put("credentials_enable_service", false);
prefs.put("profile.password_manager_enabled", false);
options.setExperimentalOption("prefs", prefs);
options.addArguments("enable-automation");
options.addArguments("--headless");
options.addArguments("--window-size=1920,1080");
options.addArguments("--no-sandbox");
options.addArguments("--disable-extensions");
options.addArguments("--dns-prefetch-disable");
options.addArguments("--disable-infobars");
options.addArguments("--disable-dev-shm-usage");
options.addArguments("--disable-browser-side-navigation");
options.addArguments("enable-features=NetworkServiceInProcess");
options.addArguments("--disable-gpu");
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
return capabilities;
}
}
private WebDriver getLocalDriver() {
switch (getAveaConfiguration().getBrowser()) {
case "chrome":
return new ChromeDriver();
// case "ie":
// return new InternetExplorerDriver(getCapabilitiesForIe());
default:
return new ChromeDriver();
}
}
I solved my problem but forget to close my question. The problem is google chrome files moved to another path by someone. Install the chrome again and problem solved.
Related
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(); ```
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/
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 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");
Class1:
public class LaunchApp {
AndroidDriver<WebElement> driver;
#BeforeTest
public void Test1() throws MalformedURLException {
DesiredCapabilities capability = new DesiredCapabilities();
capability.setCapability("deviceName", "Android");
capability.setCapability("platformName", "Android");
capability.setCapability("platformVersion", "5.1.1");
capability.setCapability("deviceName", "Samsung Galaxy On5");
capability.setCapability("app",
"D:\\whatsapp.apk");
capability.setCapability("PackageName",
"com.movocado.socialbostonsports");
capability.setCapability("ActivityName",
"com.movocado.socialbostonsports.Activity.LogInSceen");
try {
driver = new AndroidDriver<WebElement>(new URL(
"http://127.0.0.1:4723/wd/hub"), capability);
} catch (MalformedURLException e) {
e.printStackTrace();
}
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
Class2:
public class DrawerMenuTest {
AndroidDriver<WebElement> driver;
#Test(priority = 1)
public void DrawerMenuIcon() {
WebElement drawerMenu = driver.findElement(By
.id("com.movocado.socialbostonsports:id/rel_drawer"));
try {
drawerMenu.click();
} catch (NullPointerException e) {
System.out.println(e.getMessage());
}
}
Problem:
Second class is showing NullPointerException. Suggest me a solution.
You are initializing AndroidDriver into LaunchApp but does not pass this driver reference into DrawerMenuTest where you are creating only refrence variable of AndroidDriver with null that's causes of NullPointerException.
To overcome it you should create separate singlton class which will give single instance of AndroidDriver to each and every class as below :-
public class DriverInit {
private AndroidDriver<WebElement> driver;
private static DriverInit driverInit = null;
public static DriverInit getInstance() {
if (driverInit == null) {
driverInit = new DriverInit();
}
return driverInit;
}
private DriverInit() {
DesiredCapabilities capability = new DesiredCapabilities();
capability.setCapability("deviceName", "Android");
capability.setCapability("platformName", "Android");
capability.setCapability("platformVersion", "5.1.1");
capability.setCapability("deviceName", "Samsung Galaxy On5");
capability.setCapability("app", "D:\\whatsapp.apk");
capability.setCapability("PackageName", "com.movocado.socialbostonsports");
capability.setCapability("ActivityName", "com.movocado.socialbostonsports.Activity.LogInSceen");
this.driver = new AndroidDriver<WebElement>(new URL(
"http://127.0.0.1:4723/wd/hub"), capability);
this.driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
public WebDriver getDriver() {
return this.driver;
}
}
Now you can use this into LaunchApp class as below :-
public class LaunchApp {
AndroidDriver<WebElement> driver;
#BeforeTest
public void Test1() throws MalformedURLException {
driver = DriverInit.getInstance().getDriver();
//now do your stuff with this driver
}
}
And use in DrawerMenuTest class as below :-
public class DrawerMenuTest {
AndroidDriver<WebElement> driver;
#Test(priority = 1)
public void DrawerMenuIcon() {
//get driver instance first
driver = DriverInit.getInstance().getDriver();
WebElement drawerMenu = driver.findElement(By
.id("com.movocado.socialbostonsports:id/rel_drawer"));
try {
drawerMenu.click();
} catch (NullPointerException e) {
System.out.println(e.getMessage());
}
}
}
Hope it helps..:)