Selenium Browser keeps dying on me - selenium

I see other people have been having this issue, by mine seems a bit different than anyone elses as it only is occuring when I run a full suite (fails on like test 20).
if I run a single test or only a few test, the code works just fine.
Otherwise, I get the following stack trace:
org.openqa.selenium.remote.UnreachableBrowserException: Error communicating with the remote browser. It may have died.
I am running my code locally and I don't know why it doesn't try to create a new browser. Instead, it just skips all the remaining cucumber steps.
Does anyone know why this would happen?
Here is my setup and teardown steps:
public class Setup_Teardown_steps extends BaseStepClass {
#Before("#selenium")
public void selenium_before_step(Scenario scenario) { //Function responsible for setting the scenario start and global end condition
//Selenium setup
//initialize_selenium_elements();
driver = WebDriver_Singleton.getNewDriver(); //Creates a new Webdriver instance.
driver.manage().window().setSize(new Dimension(1280, 800));
startTime = System.currentTimeMillis();
testData.ClearTestData(); //Clears saved test data
testData.current_scenario = scenario;
}
/**
* After each scenario Hook (except report scenarios) - public cause it has to be.
*/
#After("#selenium")
public void selenium_after_step(Scenario scenario) throws IOException {
endTime = System.currentTimeMillis();
scenario.write("Run time = " + (endTime - startTime)/1000 + " seconds");
if (scenario.isFailed()){
String html_link = driver.getCurrentUrl();
scenario.write("\n");
scenario.write("URL = " + html_link);
try {
byte[] screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
scenario.embed(screenshot, "image/png");
} catch (WebDriverException wde) {
System.err.println(wde.getMessage());
} catch (ClassCastException cce) {
cce.printStackTrace();
}
}
driver.close(); //Clears cache and cookies
testData.ClearTestData(); //Clears saved test data
}
}
//WebDriver_Singleton Function below
private static WebDriver create_driver(){
if (driver != null){
driver.close();
}
assign_base_urls();
String browser = System.getProperty("browser") == null ? "ff" : System.getProperty("browser");
switch(browser.toLowerCase()){
case "ff":
case "firefox":
case "mozilla":
driver = new FirefoxDriver();
break;
case "ie":
case "internet explorer":
case "internet_explorer":
driver = new InternetExplorerDriver();
break;
case "chrome":
case "google":
driver = new ChromeDriver();
break;
default:
System.out.println("Defaulting to Firefox browser");
driver = new FirefoxDriver();
}
driver.manage().timeouts().implicitlyWait(implicit_wait_timeouts, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(page_load_timeouts, TimeUnit.SECONDS);
driver.manage().timeouts().setScriptTimeout(script_timeouts, TimeUnit.SECONDS);
return driver;
}

I looked at the stack trace, was hard to find but the jenkins server was running out of memory.

Related

How to Launch and Switch between two browsers(not tabs) chrome and firefox drivers in Selenium Java

#Test
public void openWeb() throws IOException, InterruptedException {
fis = new FileInputStream(System.getProperty("user.dir")+"\\resources\\config.properties");
property = new Properties();
property.load(fis);
WebElement UsernameField = driver.findElement(By.name(property.getProperty("username_fieldName")));
WebElement PasswordField = driver.findElement(By.name(property.getProperty("password_fieldName")));
WebElement SubmitButton = driver.findElement(By.xpath(property.getProperty("submit_ButtonXpath")));
UsernameField.click();
UsernameField.sendKeys("test");
PasswordField.click();
PasswordField.sendKeys("!TEST");
SubmitButton.click();
//Testcase TC_1.01 Verify the login of "Berater" with valid credentials
WebElement Einladen = driver.findElement(By.className(property.getProperty("HomeScreen_EinladenClass")));
boolean Homescreen = Einladen.isDisplayed();
extentTest = extent.startTest("TC_1.01 - Verify the login of \"Berater\" with valid credentials");
if(Homescreen == true) {
extentTest.log(LogStatus.PASS, "Login successful for the Berater");
}
else {
extentTest.log(LogStatus.FAIL, "Login Failed for the Berater, Please refer the Screenshot");
}
Thread.sleep(1000);
Einladen.click();
driver.findElement(By.xpath(property.getProperty("Einladung_LinkXpath"))).click();
Thread.sleep(1000);
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");
Thread.sleep(2000);
Actions actions = new Actions(driver);
actions.sendKeys(Keys.chord(Keys.LEFT_CONTROL, "v")).build().perform();
Thread.sleep(2000);
actions.sendKeys(Keys.ENTER);
Thread.sleep(2000);
}
First of all i call here chrome driver and open a link in chrome, now after performing some actions in chrome driver, i need to open firefox and open a separate link, and check the syncronization between the two. But i dont know how to open two different browsers and switch between them.
Please help.

WinAppDriver could not find element sometimes

WinAppDriver sometimes find element, sometimes no... I try to log my elements List size, and when I run my test sometimes it return 1, sometimes 0. My code:
public class Test {
public WindowsDriver<RemoteWebElement > driver;
#Before
public void setup() {
try {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("app", "C:\\Program Files\\App\\Bin\\MainFrame.exe");
capabilities.setCapability("platformName", "Windows");
capabilities.setCapability("deviceName", "WindowsPC");
driver = new WindowsDriver<RemoteWebElement>(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
}catch(Exception e){
e.printStackTrace();
} finally {
}
}
#Test
public void listLength() {
System.out.println(driver.findElementsByClassName("MaskEdit").size());
}
}
In log I see NoSuchElementException:
org.openqa.selenium.NoSuchElementException: An element could not be located on the page using the given search parameters. (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 2.04 seconds
The application MainFrame.exe always runs correctly but test always returns different result.
Why is this happening?
this may happen if the application may not be properly loaded at time , try adding explicit wait.

UnReachableBrowserException in Chome with Selenium Webdriver

i am getting UnhandledBrowserException when trying the below code in chrome:
public class myClass {
public static void main(String[] args) {
// declaration and instantiation of objects/variables
System.setProperty("webdriver.chrome.driver", "C://Program Files (x86)//Google//Chrome//Application//chrome.exe");
WebDriver driver= new ChromeDriver();
String baseURL = "http://newtours.demoaut.com";
String expectedTitle = "Welcome: Mercury Tours";
String actualTitle = "";
// launch Firefox and direct it to the Base URL
driver.get(baseURL);
// get the actual value of the title
actualTitle = driver.getTitle();
/*
* compare the actual title of the page witht the expected one and print
* the result as "Passed" or "Failed"
*/
if (actualTitle.contentEquals(expectedTitle)){
System.out.println("Test Passed!");
} else {
System.out.println("Test Failed");
}
//close Firefox
driver.close();
// exit the program explicitly
System.exit(0);
}
It is launching a new session in chrome but then throwing the exception. Any help would be highly appreciated.
I think you are hitting program executable instead of driver.
System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
WebDriver driver = new ChromeDriver();
It should be path to chrome driver not the chrome browser executable.
You can take a look at https://sites.google.com/a/chromium.org/chromedriver/getting-started

Responce time for steps (WebDriver + Jmeter)

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

Wait for page loading using PageFactory C#

I'm using PageFactory in my selenium tests. And I've faced a problem in waiting for loading page. I'm not talking about an element on a page I'm talking about timeout of page loading.
So, I have a method like the following:
public MyProjectsPage ClickSaveAndCloseButton()
{
//Do something and click a button
SaveAndCloseButton.Click();
return new MyProjectsPage(Driver); //return new page
}
And when I'm waiting for returning new PageObject (in my case it is "MyProjectsPage") I got a timeout exception. So, where can I set a page loading timeout?
Actual mistake looks like this:
AutomatedTests.FrontEnd.SouvenirProduct.SouvenirTestExecution.OrderSouvenirWithAuthorization(ByCash,Pickup,True,Cup):
OpenQA.Selenium.WebDriverException : The HTTP request to the remote WebDriver server for URL http://localhost:7585/session/b68c04d1ead1fc78fe083e06cbece38f/element/0.46564483968541026-14/click timed out after 60 seconds.
----> System.Net.WebException : The operation has timed out
I have:
The latest version of WebDriver
And the latest version of ChromeDriver and the latest version of Chrome Browser
The mistake that is above apears int the next line:
return new MyProjectsPage(Driver); //return new page
I create my ChromeDriver the next way:
public DriverCover(IWebDriver driver)
{
_driver = driver;
_driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
}
private readonly IWebDriver _driver;
1 note considering wait mechanisms on the page:
Take a couple of webElements and apply for them fluentWait() . That'll be explicit wait webdriver approach.
Another approach is to try out implicit wait like:
int timeToWait=10;
driver.manage().timeouts().implicitlyWait(timeToWait, TimeUnit.SECONDS);
Considering you pageObject code:
I would recommed you the following:
MyPage myPageInstance= PageFactory.initElements(driver, MyPage.class);
then you write the following method :
public MyPage clickSaveAndOtherActions(MyPage testPageToClick)
{
testPageToClick.clickFirstButton();
testPageToClick.clickSecondButton();
testPageToClick.closePoPup();
return testPageToClick; //return page in a new state
}
and if you wanna continue working (I mean update your page state) you do the following:
myPageInstance = clickSaveAndOtherActions(myPageInstance );
Hope this helps you. Thanks.
UPD : as I see from the log something looks wrong with remoteWebdriver server:
OpenQA.Selenium.WebDriverException : The HTTP request to the remote
WebDriver server for URL
http://localhost:7585/session/b68c04d1ead1fc78fe083e06cbece38f/element/0.46564483968541026-14/click
timed out after 60 seconds. ----> System.Net.WebException : The
operation has timed out
Also, I'd recommend you to double check you driver method init. I'm using the following piece of java code for driver init (UI , chrome instance, selenium grid+ hub nodes test architecture):
public static WebDriver driverSetUp(WebDriver driver) throws MalformedURLException {
DesiredCapabilities capability = DesiredCapabilities.chrome();
log.info("Google chrome is selected");
//System.setProperty("webdriver.chrome.driver", System.getProperty("user.home")+"/Documents/Tanjarine/chromedriver");
System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
capability.setBrowserName("chrome");
capability.setPlatform(org.openqa.selenium.Platform.WINDOWS);
String webDriverURL = "http://" + environmentData.getHubIP() + ":" + environmentData.getHubPort() + "/wd/hub";
driver = new RemoteWebDriver(new URL(webDriverURL), capability);
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
driver.manage().window().setSize(new Dimension(1920, 1080));
return driver;
}
What you should really be doing when using the PageFactory pattern is when initialising your Page you should be using a constructor to initialise the elements.
public MyProjectsPage ClickSaveAndCloseButton()
{
//Do something and click a button
//I am guessing this is taking you to the MyProjectsPage
SaveAndCloseButton.Click();
return new MyProjectsPage(Driver); //return new page
}
public class MyProjectsPage
{
[FindsBy(How = How.Id, Using = "yourId")]
public IWebElement AWebElement { get; set; }
private IWebDriver WebDriver;
public MyProjectsPage (IWebDriver webDriver)
{
WebDriver = webDriver;
PageFactory.InitElements(WebDriver, this);
}
}
When you return the page, all elements using the FindsBy attribute will be initialised.
Update:
set this property on the driver when you initialise it:
WebDriver.Manage().Timeouts().SetPageLoadTimeout(timespan)
// Wait Until Object is Clickable
public static void WaitUntilClickable(IWebElement elementLocator, int timeout)
{
try
{
WebDriverWait waitForElement = new WebDriverWait(DriverUtil.driver, TimeSpan.FromSeconds(10));
waitForElement.Until(ExpectedConditions.ElementToBeClickable(elementLocator));
}
catch (NoSuchElementException)
{
Console.WriteLine("Element with locator: '" + elementLocator + "' was not found in current context page.");
throw;
}
}
// Wait For Page To Load
public static void WaitForPage()
{
new WebDriverWait(DriverUtil.driver, MyDefaultTimeout).Until(
d => ((IJavaScriptExecutor)d).ExecuteScript("return document.readyState").Equals("complete"));
}