Setting timeout with testNG and Selenium in Java - java

I've got a problem with testing in Java. I'm using TestNG & Selenium. I wanted to run a method with annotaion #Test on long period of time, but it stopped in about 5000 seconds. I've tried to set attribute Timeout, but it didn't work for me. How can I control execution time of test method?
Sometimes I've noticed that my test method before stop after around 5000 seconds threw exception "org.openqa.selenium.remote.SessionNotFoundException: Session ID is null".

Use WebDriver Wait and Wait Until Expected Conditions before Performing Any Action on Any Element, So that testcases Never Fails due to Timing Issues
WebDriverWait wait = new WebDriverWait(driver, 80);// Maximum TimeOut
PageUtil.refreshObject(driver, By.linkText("Link_yu_want_to_click"));
wait.until(ExpectedConditions.elementToBeClickable(By.linkText("Link_yu_want_to_click")));

Related

How to verify if Implicit wait is working in Katalon Studio

public void verifySeleniumTitle()
{
WebUI.openBrowser('https://www.google.com')
driver = DriverFactory.getWebDriver();
driver.manage().window().maximize();
driver.get("https://www.google.com");
// Specify implicit wait of 30 seconds
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
// No text is present on Webpage.
driver.findElement(By.xpath("//*[text()=\"Hello World\"]"));
}
}
Crating a new custom keyword for my test case in katalon studio, and I am creating implicit wait, the code above enables me to receive a NoSuchElement Exception Message but I do not know if the time stated in implicit wait is totally working. Can someone help me figure this out? Thank you very much!
Just see if the NoSuchElement Exception thrown immediately after opening the "https://www.google.com" URL or it waits 30 seconds as defined in your implicitlyWait and only after the 30 seconds timeout the exception is thrown.

Unable to locate elements via Selenium if ran via Bitbucket pipeline

I am currently working on integration tests in Selenium. I have some testset, which tests presence of webelements and their behaviour. Everything works perfectly if I run these tests on my local machine. As a WebDriver I use ChromeDriver.
But some of these tests fail, if I run them in pipeline on bitbucket. It fails because it was not able to locate element, the worst thing is that in pipeline it behaves sort of undeterministic - that it sometimes locate this element and sometimes it doesn't (no code changed between run in which element was found and in which element was not found, Website tested was not changed either between runs.)
Expected condition failed: waiting for presence of element located by... (tried for 300 second(s) with 500 milliseconds interval)
On my local machine, which is not really fast one, 30s timeout is perfectly enough for me. And tests always pass on my local machine. Is it that pipeline on bitbucket runs extremely slowly or do I miss something?
webDriver.get(getTerminalUrl());
WebDriverWait wait = new WebDriverWait(webDriver, 60);
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[text()='Sign In']")));
WebElement login = webDriver.findElement(By.xpath("//*[text()='Sign In']"));
login.click();
I use this kind of pattern in all my tests.
Try doing like this:
webDriver.get(getTerminalUrl());
WebDriverWait wait = new WebDriverWait(webDriver, 60);
boolean elementPresent = driver.findElements(By.xpath("//*[text()='Sign In']")).size() > 0;
if(elementPresent){
Thread.sleep(3000);
WebElement login = webDriver.findElement(By.xpath("//*[text()='Sign In']"));
Thread.sleep(3000);
login.click();
}

ExplicitWait taking more time if an element removed from DOM

I'm automating this website But facing the issue with ExplicitWaitConditions to manage the time.
Scenario is When i click on Login link or Submit button after send username, It shows a loader during the process, once process has completed the loader get removed from DOM.
I have used condition for invisibilityOfElementLocated like below
new WebDriverWait(driver, 60).until(ExpectedConditions.invisibilityOfElementLocated(By.id("loading-bar")));
But this can't predict correct time it taking more time (not exectly 60 sec but around 15-20 or may be 30 sec.) then allow to execute next command.
The same line i have to put before 4 commands to do complete login process. So it seems to consumed around 90 second to do login.
If i do not use Explicitwait or remove Impliciwait wait then script failed all time as loader get click instead of some other element.
The code i tried so far :
WebDriver driver = new FirefoxDriver();
System.out.println("Browser Opened");
driver.manage().window().maximize();
driver.get("https://www.rcontacts.in");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
System.out.println("URL Opened");
new WebDriverWait(driver, 60).until(ExpectedConditions.invisibilityOfElementLocated(By.id("loading-bar")));
driver.findElement(By.cssSelector(".ng-scope>a span[translate='login.register']")).click();
System.out.println("Register Link Clicked");
driver.findElement(By.name("userId")).sendKeys("9422307801");
new WebDriverWait(driver, 60).until(ExpectedConditions.invisibilityOfElementLocated(By.id("loading-bar")));
driver.findElement(By.xpath("//button[#type='submit']")).click();
System.out.println("Mobile number entered");
new WebDriverWait(driver, 60).until(ExpectedConditions.invisibilityOfElementLocated(By.id("loading-bar")));
Is there any solution that as soon as loader get removed it start performing actions ?
OR is there any way that I can wait until loader element get removed from DOM. Once removed then i can continue the further actions ?.
According to the docs,
WARNING: Do not mix implicit and explicit waits. Doing so can cause unpredictable wait times.
That's likely the cause of your issues. It's recommended to not use implicit waits. I would remove them and then add explicit waits as needed and see how that goes.
I took your code and rewrote it (below) and it's working every time for me.
String url = "https://www.rcontacts.in";
driver.navigate().to(url);
waitForLoader();
driver.findElement(By.cssSelector("span[translate='login.register']")).click();
waitForLoader();
driver.findElement(By.cssSelector("input[name='userId']")).sendKeys("9422307801");
driver.findElement(By.cssSelector("button[translate='common.btns.next']")).click();
The issue I was having at times was that many times the script was jumping ahead. I added code to waitForLoader() to wait for the loader to appear (be visible) and then disappear (be invisible). Once I did that, it worked 100% of the time.
public static void waitForLoader()
{
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.id("loading-bar")));
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.id("loading-bar")));
}
First and foremost, you have induced implicitlyWait() as follows:
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
As well as WebDriverWait() as follows:
new WebDriverWait(driver, 60).until(ExpectedConditions.invisibilityOfElementLocated(By.id("loading-bar")));
As per the documentation of Explicit and Implicit Waits it is clearly mentioned that:
Do not mix implicit and explicit waits. Doing so can cause unpredictable wait times. For example setting an implicit wait of 10 seconds and an explicit wait of 15 seconds, could cause a timeout to occur after 20 seconds.
Again, it seems changing the ExpectedConditions clause from invisibilityOfElementLocated(By.id("loading-bar") to elementToBeClickable(By.xpath("//span[contains(text(),'Register')]") gives me a success rate of 80%. Here is the effective code block on my Windows 8 box:
System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.rcontacts.in");
System.out.println("URL Opened");
WebDriverWait wait = new WebDriverWait (driver, 15);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//span[contains(text(),'Register')]")));
driver.findElement(By.xpath("//span[contains(text(),'Register')]")).click();
System.out.println("Register Link clicked");
Note: Always invoke driver.quit() within tearDown(){} method to close & destroy the WebDriver and Web Client instances gracefully to ensure that no dangling instance of geckodriver is present (through Task Manager) while you initiate the execution.

Appium's implicitlyWait does not work

I am using Appium to automate an iOS app but met a problem, is there anyone meet the same problem before?
Appium's implicitlyWait API seems to not work. I am using Java and JUnit to run the test, here is the line of code:
driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
I have checked the debug info in the appium console, it looks correctly:
info: [debug] Set iOS implicit wait to 50000ms
My Environment:
Latest Appium 1.2.1, Java client library 1.6.1, Selenium Java language binding 2.42.2 and sample app 'UICatalog'provided by Sauce Lab.
Thanks in advance for the reply.
The code you have posted manages the timeout to wait for a maximum of 50 seconds. It doesn't make the driver wait 50 seconds. You can use the wait like:
driver.wait(); //this will wait a max of 50 seconds cuz you said so
If you ask me the proper way you would want to use waiting on Webdriver is:
WebDriverWait wait;
wait = new WebDriverWait(driver, 60);
wait.until(ExpectedConditions.elementToBeClickable(By.id("blabla"));
The code above checks if blabla is clickable until that condition is proved or 60 seconds(stated above) passes the driver waits.
In Appium it is possible to set implicit way in this way:
Java code:
AppiumFieldDecorator decorator = new AppiumFieldDecorator(driver);
decorator.resetImplicitlyWaitTimeOut(50, TimeUnit.SECONDS);
PageFactory.initElements(decorator, this /* refers to current page object class*/);
Such timeout will work for the whole time.
It is not possible (at least I don't know) to change it.
As when web drivers are used you can do this with:
driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
// some actions for which you don't want to wait implicitly
driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
Try this:
public static void WaitForElementPresent1(String locator, int timeout)
{
WebDriverWait wait = new WebDriverWait(driver, timeout);
try{
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(locator)));
} catch (Exception e){
e.printStackTrace();
}
}
If you are using PageFactory model, you can specify the implicit wait with initElements() method as given below -
PageFactory.initElements(new AppiumFieldDecorator(driver, 10, TimeUnit.SECONDS), this);
I have tried this with Appium 1.6 and it works fine.
The new way of setting the implicit time out is using the code
AppiumFieldDecorator decorator = new AppiumFieldDecorator(mobDriver);
decorator.DEFAULT_IMPLICITLY_WAIT_TIMEOUT = longValue;
decorator.DEFAULT_TIMEUNIT = TimeUnit.TimeUnit ;
Hope this helps

How do I set the selenium webdriver get timeout?

When I am using a proxy in webdriver like FirefoxDriver, if the proxy is bad then the get method will block forever. I set some timeout parameters, but this did not work out.
This is my code:
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("general.useragent.override", ua);
Proxy p = new Proxy();
p.setHttpProxy(proxy);
profile.setProxyPreferences(p);
profile.setEnableNativeEvents(true);
// create a driver
WebDriver driver = new FirefoxDriver(profile);
driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
driver.manage().timeouts().setScriptTimeout(30, TimeUnit.SECONDS);
driver.get("www.sina.com.cn")
The call to driver.get will block for ever, but I want it to wait for 30 seconds and if the page is not loaded then throw an exception.
Try this:
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
The timeouts() methods are not implemented in some drivers and are very unreliable in general.
I use a separate thread for the timeouts (passing the url to access as the thread name):
Thread t = new Thread(new Runnable() {
public void run() {
driver.get(Thread.currentThread().getName());
}
}, url);
t.start();
try {
t.join(YOUR_TIMEOUT_HERE_IN_MS);
} catch (InterruptedException e) { // ignore
}
if (t.isAlive()) { // Thread still alive, we need to abort
logger.warning("Timeout on loading page " + url);
t.interrupt();
}
This seems to work most of the time, however it might happen that the driver is really stuck and any subsequent call to driver will be blocked (I experience that with Chrome driver on Windows). Even something as innocuous as a driver.findElements() call could end up being blocked. Unfortunately I have no solutions for blocked drivers.
try
driver.executeScript("window.location.href='http://www.sina.com.cn'")
If you have set pageLoadStrategy to none, this statement will return immediately.
And after that , you can add a WebDriverWait with timeout to check if the page title or any element is ok.
Hope this will help you.
I had the same problem and thanks to this forum and some other found the answer.
Initially I also thought of separate thread but it complicates the code a bit. So I tried to find an answer that aligns with my principle "elegance and simplicity".
Please have a look at such forum:
https://sqa.stackexchange.com/questions/2606/what-is-seleniums-default-timeout-for-page-loading
#
SOLUTION:
In the code, before the line with 'get' method you can use for example:
driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
#
One thing is that it throws timeoutException so you have to encapsulate it in the try catch block or wrap in some method.
I haven't found the getter for the pageLoadTimeout so I don't know what is the default value, but probably very high since my script was frozen for many hours and nothing moved forward.
#
NOTICE:
'pageLoadTimeout' is NOT implemented for Chrome driver and thus causes exception. I saw by users comments that there are plans to make it.
You can set the timeout on the HTTP Client like this
int connectionTimeout=5000;
int socketTimeout=15000;
ApacheHttpClient.Factory clientFactory = new ApacheHttpClient.Factory(new HttpClientFactory(connectionTimeout, socketTimeout));
HttpCommandExecutor executor =
new HttpCommandExecutor(new HashMap<String, CommandInfo>(), new URL(seleniumServerUrl), clientFactory);
RemoteWebDriver driver = new RemoteWebDriver(executor, capabilities);
The solution of driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS) will work on the pages with synch loading. This does not solve, however, the problem on pages loading stuff in async, then the tests will fail all the time if we set the pageLoadTimeOut.
I find that the timeout calls are not reliable enough in real life, particularly for internet explorer , however the following solutions may be of help:
You can timeout the complete test by using #Test(timeout=10000) in the junit test that you are running the selenium process from. This will free up the main thread for executing the other tests, instead of blocking up the whole show. However even this does not work at times.
Anyway by timing out you do not intend to salvage the test case, because timing out even a single operation might leave the entire test sequence in inconsistent state. You might just want to proceed with the other testcases without blocking (or perhaps retry the same test again). In such a case a fool-proof method would be to write a poller that polls processes of Webdriver (eg. IEDriverServer.exe, Phantomjs.exe) running for more than say 10 min and kill them. An example could be found at Automatically identify (and kill) processes with long processing time
Used below code in similar situation
driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
and embedded driver.get code in a try catch, which solved the issue of loading pages which were taking more than 1 minute.

Categories