Running Selenium tests with Chrome on Ubuntu in a headless environment - java

There's a massive amount of postings on this topic, but for some reason, I've found little relating to Chrome (it seems the support was recently added for headless). The tests work running locally with a browser.
Is it possible to trigger an Xvfb display from Java so I can manage everything in one place? I'd rather not have to do:
Xvfb :1 -screen 0 1024x768x24 &
Via the command line. It'd be useful to run a display, then shut it down.
SetEnvironmentProperty to ChromeDriver programatically is what I found to be the solution.
The problem? I can't get it to work on an Ubuntu machine.
The error I receive is:
/home/ubuntu/myproject/conf/chromedriver: 1: Syntax error: Unterminated quoted string
The test class I'm using:
import java.io.File;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import play.Logger;
import utils.LocalInfo;
import com.google.common.collect.ImmutableMap;
public class TestCI {
private WebDriver driver;
#SuppressWarnings("deprecation")
public TestCI(String url) {
if (!LocalInfo.isEC2()) {
Logger.info("Running tests by opening a browser...");
System.setProperty("webdriver.chrome.driver", "conf/chromedriver");
setWebDriver(new ChromeDriver());
} else {
Logger.info("Running tests headlessly...");
String xPort = System.getProperty("Importal.xvfb.id", ":1");
ChromeDriverService service = new ChromeDriverService.Builder()
.usingChromeDriverExecutable(new File("conf/chromedriver"))
.usingAnyFreePort()
.withEnvironment(ImmutableMap.of("DISPLAY", xPort)).build();
setWebDriver(new ChromeDriver(service));
}
getWebDriver().get("http://www.google.com");
try {
someUITest();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
getWebDriver().close();
}
public WebDriver getWebDriver() {
return driver;
}
public void setWebDriver(ChromeDriver driver) {
this.driver = driver;
}
public void someUITest() throws Exception {
getWebDriver().findElement(By.name("q"));
}
}

I switched to the chromedriver for linux and it got rid of the unterminated quoted string error http://code.google.com/p/chromedriver/downloads/list

Related

Multiple login sessions not getting closed with driver.close in java-selenium

I have added code snippet for further clarity.
I am using java-selenium-testNG and trying to login to a website zoho.com with 3 accounts and verifying if success. I have looked through somewhat similar issues but haven't found a solution that works in my case.
I instantiate the ChromeDriver in #BeforeMethod. Then I login to the website with first account and close the browser in my #AfterMethod.
I have to re-instantiate the browser with Driver = new ChromeDriver to login back with a new account as the instance is closed or atleast that's the feeling it gives error that the session id doesn't exists.
My issue is only the last instance of the driver is getting closed as I have driver.quit in the #AfterTest method. The other two instances remain in memory.
I have also tried using the same instance without closing the browser but in such cases the login option is not available on that particular website and my subsequent tests fail.
here is the code below for further clarification
package uk.dev.test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.*;
import io.github.bonigarcia.wdm.WebDriverManager;
import java.util.concurrent.TimeUnit;
public class zohoLogin {
WebDriver driver=null;
String winHandleBefore;
#DataProvider(name ="testData")
public Object[][] loginPasswordData()
{
return new Object[][]{
{"xxx#gmail.com",new String ("somepassword")} ,
{"yyy#gmail.com",new String ("somepassword")},
{"zzz#gmail.com",new String ("somepassword")},
};
}
#Test ( dataProvider = "testData")
public void enterUserDetails(String userEmail, String userPassword) throws InterruptedException {
driver.findElement(By.xpath("//input[#id='login_id']")).sendKeys(userEmail);
System.out.println(("Running for Test data " + userEmail));
Thread.sleep(2000);
driver.findElement(By.xpath("//button[#id='nextbtn']")).click();
Thread.sleep(2000);
System.out.println("clicked on Next");
driver.findElement(By.xpath("//input[#id='password']")).sendKeys(userPassword);
System.out.println("Entered the password");
driver.findElement(By.xpath("//button[#id='nextbtn']//span[contains(text(),'Sign in')]")).click();
System.out.println("Clicked on Signin");
Thread.sleep(2000);
}
#BeforeMethod
public void loginZoho() throws InterruptedException
{
driver = new ChromeDriver();
driver.get("https://www.zoho.com");
System.out.println("Open the browser");
driver.findElement(By.xpath("//a[#class='zh-login']")).click();
//driver.manage().timeouts().implicitlyWait(5000, TimeUnit.MILLISECONDS);
Thread.sleep(5000);
}
#AfterMethod
public void closeBrosers() throws InterruptedException {
Thread.sleep(2000);
driver.close();
System.out.println("Close the browser");
}
#BeforeTest
public void setupBrowser()
{ WebDriverManager.chromedriver().setup();
}
#AfterTest
public void tearDown()
{
driver.quit();
}
}
Attached the run results where 2 chrome driver instance can be seen.Also note the AfterMethod is not getting executed.
enter image description here
I am using driver.quit() method in selenium but facing the same issue. I think issue is related to the latest version of chromedriver.
public static void CloseDriver()
{
if (Driver != null)
{
Driver.Quit();
Driver = null;
}
}
I even tried Driver.Kill() but it resulted in closing all the browsers.

Using Jdk 10 and Oxygen 3a

In the following program the 2nd and 3rd import statements are erroring out by the following statement - The package org.openqa.selenium is accessible from more than one module: client.combined, com.google.common.
The following are the jar files I added to module path.
Program with errors
After compilation
This program was running successfully with jdk 9 and oxygen. But its is failing now. Please let me know what corrections I can do to use the webdriver in my project.
Thanks in Advance.
package javaExamples;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
public class FirstTrial {
WebDriver driver;
JavascriptExecutor jse;
public void invokeBrowser() {
try {
System.setProperty("webdriver.chrome.driver",
"C:\\Selenium\\chromedriver_win32_2018_april\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().deleteAllCookies();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);// allows system to wait max 30 secs if it
// completes before its fine
driver.get("http://www.edureka.co");
searchBrowser();
} catch (Exception e) {
e.printStackTrace();
}
}
public void searchBrowser() {
driver.findElement(By.id("homeSearchBar")).sendKeys("java");
// Thread.sleep(2000);//allows to wait for 2 secs. This is
explicit wait. System // must sleep for 2 secs
driver.findElement(By.id("homeSearchBarIcon")).click();
jse = (JavascriptExecutor) driver;
jse.executeScript("scroll(0,600)");
driver.findElement(By.xpath("//label[contains(text(),'Weekend')]")).click();
}
public static void main(String[] args) {
FirstTrial myobj = new FirstTrial();
myobj.invokeBrowser();
}
}

AssertionViolatedException still occur using eclipse

I tried running this code in my laptop. I followed all the instruction showed in Edureka in youtube. Tried uninstall and reinstalling method. I transferred files from a laptop where the code work and yet, still no good.
package testing;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import net.bytebuddy.asm.Advice.Enter;
public class test_1 {
WebDriver driver;
public void invokeBrowser() {
try {
System.setProperty("webdriver.chrome.driver", "D:\\Program Files (x86)\\Files\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().deleteAllCookies();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
driver.get("http://google.com/");
LogIn();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
test_1 myObj = new test_1();
myObj.invokeBrowser();
}
}
then here's the error
Exception in thread "main"
org.apache.bcel.verifier.exc.AssertionViolatedException:
FOUND:
INTERNAL ERROR: Oops!
Exiting!!
at
org.apache.bcel.verifier.exc.AssertionViolatedException.main(AssertionViolatedException.java:102)

ChromeDriver cannot navigate to URL in eclipse

I am very new to Cucumber and get the following error using ChromeDriver to request a URL:
java.lang.IllegalStateException: The path to the driver executable
must be set by the webdriver.chrome.driver system property; for more
information, see http://code.google.com/p/selenium/wiki/ChromeDriver.
The latest version can be downloaded from
http://chromedriver.storage.googleapis.com/index.html at
com.google.common.base.Preconditions.checkState(Preconditions.java:177)
My code:
package cucumber.features;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class AddToList {
WebDriver driver = null;
#Given("^I am on Todo site$")
public void onSite() throws Throwable {
driver = new ChromeDriver();
driver.navigate().to("http://localhost");
System.out.println("on todo site");
}
#When("^Enter a task in todo textbox$")
public void enterTask() throws Throwable {
driver = new ChromeDriver();
driver.findElement(By.name("task")).sendKeys("Test Unit Using Cucumber");
;
System.out.println("task entered");
}
#Then("^I click on add to todo$")
public void clickAddToTodo() throws Throwable {
driver = new ChromeDriver();
driver.findElement(By.xpath("//input[#value='Add to Todo' and #type='button']"));
System.out.println("add button clicked");
}
}
I had a similar problem when using selenium library. I found this line before creating my driver fixed it.
System.setProperty("webdriver.chrome.driver", PATH_TO_CHROME_DRIVER);
Here is simple project that could help you.
this.driver.get(URL);
Also, I don't think your When and Then should create new ChromeDrivers. Only the Given. I use the setUp method to instantiate it
#Before
public void setUp() {
System.setProperty("webdriver.chrome.driver", "..//..//files//drivers//chromedriver.exe");
this.driver = new ChromeDriver();
}

Selenium HtmlUnitDriver hangs randomly in random places

I used SeleniumHQ to record my actions and then exported them to Java Unity WebDrive. Then I edited exported code and added many small extra things like looping over array, time-stamps, etc.
My code does following:
Log into my site.
Goto my profile.
Delete my previous announcement.
Post new announcement.
Log out.
I have tried using FirefoxDriver and HtmlUnitDriver, but every single of them gives me this weird problem. My code start doing its work and randomly stops in random spot and hangs there forever.
For example it could log in -> goto profile -> delete previous and then stop, or it could hang right in the login. I loop over those steps over and over again, and more I loop more likely it is to get stuck.
First loops success rate is 90% second loop is around 40% etc. Also which Driver I use also affects this. It is most likely to hang with HtmlUnitDriver and I would really want to use HtmlUnitDrive because I want to run my code headless on Ubuntu Server.
Has anyone else had similar problems?
EDIT : Now after many hours of testing, I noticed that its only HtmlUnitDriver that hangs and not Firefox. When using Firefox I can see what it is doing and it is doing everything as it should. Problem occurs with HtmlUnitDriver.
And here is the code itself:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import org.openqa.selenium.*;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
public class WebUpdater {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
driver = new HtmlUnitDriver(true); // JavaScript enabled.
baseUrl = "http://exampleurl.com";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testUnity() throws Exception {
openAndLogin();
gotoProfile();
deletePreviousPost();
uploadPost();
logOut();
System.out.println("Done!");
}
private void openAndLogin() {
driver.get(baseUrl);
driver.findElement(By.linkText("Login")).click();
driver.findElement(By.id("jsid-login-id")).clear();
driver.findElement(By.id("jsid-login-id")).sendKeys("bilgeis.babayan#gmail.com");
driver.findElement(By.id("jsid-login-password")).clear();
driver.findElement(By.id("jsid-login-password")).sendKeys("volume1991");
driver.findElement(By.cssSelector("input.right")).click();
}
private void gotoProfile() {
driver.findElement(By.cssSelector("img[alt=\"Profile\"]")).click();
}
private void deletePreviousPost() {
try {
driver.findElement(By.cssSelector("img[alt=\"ExampleName\"]")).click();
driver.findElement(By.linkText("Delete")).click();
assertTrue(closeAlertAndGetItsText().matches("^Confirm to delete this post[\\s\\S]$"));
} catch (Exception e) {
System.out.println(e);
}
}
private void uploadPost() {
driver.findElement(By.linkText("ExampleAction")).click();
driver.findElement(By.id("example_url")).clear();
driver.findElement(By.id("example_url")).sendKeys("Example text that gets typed in textfield.");
driver.findElement(By.cssSelector("input[name=\"example\"]")).clear();
driver.findElement(By.cssSelector("input[name=\"example\"]")).sendKeys("ExampleName");
driver.findElement(By.linkText("ExampleAction2")).click();
System.out.println("Done");
}
private void logOut() {
driver.get("http://exampleurl.com/logout");
System.out.println("Logged out.");
}
#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;
}
}
}
in my main class I call WebUpdater class like this:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Main {
public static void main(String[] args) {
Logger logger = Logger.getLogger("");
logger.setLevel(Level.OFF);
scan();
}
private static void scan() {
while (true) {
try {
// Test if connection is available and target url is up.
URL url = new URL("http://exampleurl.com");
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.connect();
// Start tests.
WebUpdater updater = new WebUpdater();
updater.setUp();
updater.testUnity();
updater.tearDown();
} catch (Exception ex) {
System.out.println(ex);
}
try {
Thread.sleep(12000);
} catch (InterruptedException e) {
}
}
}
}
I had a bad experience with HtmlUnitDriver. Some time ago I wrote testing framework which were supposed to be fired at Hudson, and finally I decided to use Firefox driver which was more predictable and easier to debug. The point is that in my case it was a page full of javascripts - dynamically loaded fields, etc., and working with HtmlUnitDriver was really a can of worms.
If you really need to use HtmlUnitDriver try do debug 'pagesource' which is accessible for Selenium in 'current' (hanging) moment.
HtmlUnit 2.11 is flawed (see here and here), and since HtmlUnit 2.12 went live march 6th, the current version of HtmlUnitDriver is probably still based on HtmlUnit 2.11.
If you post your "http://exampleurl.com/" source code (or just give me a working url to the page if it's public) I could run the page with scripts through HtmlUnit 2.12.

Categories