Selenium Testing : If element is not present then exception is not handled by Exception of type NoSuchElementException in Selenium - selenium

If any element doesnot exists in Selenium Testing, then I am unable to handle it. I have tried this code.
public static bool IsElementPresent(IWebDriver driver, By by)
{
try
{
driver.FindElement(by);
return true;
}
catch (NoSuchElementException)
{
return false;
}
catch (Exception ex)
{
return false;
}
}
It shows timeout exception takes too much time more than 1 min and finally handled by main Exception class, but my automation testing stops, And I dont want to stop my testing.
I have tried this code snippet also.
public bool IsElementPresent(IWebDriver driver, By by, TimeSpan? timeSpan)
{
bool isElementPresent = false;
try
{
if (timeSpan == null)
{
timeSpan = TimeSpan.FromMilliseconds(2000);
}
var driverWait = new WebDriverWait(driver, (TimeSpan)timeSpan);
driverWait.IgnoreExceptionTypes(typeof(WebDriverTimeoutException));
isElementPresent=driverWait.Until(x => x.FindElements(by).Any());
return isElementPresent;
}
catch (NoSuchElementException nex)
{
return false;
}
catch (Exception ex)
{
return false;
}
}
What should I do so that in small span of time it returns true or false.

Another option would be something like
return driver.FindElements(by).length > 0;

I generally use the Displayed property. I use the page object model with pre-determined IWebElements in the example below:
public bool IsPageObjectPresent(IWebElement PageObject)
{
try
{
if (PageObject.Displayed)
{
Console.WriteLine("Element is displayed");
return true;
}
else
{
Console.WriteLine("Element present but not visible");
return true;
}
}
catch (NoSuchElementException)
{
Console.WriteLine("Element not present");
return false;
}
catch (StaleElementReferenceException)
{
Console.WriteLine("Stale element present");
return false;
}
}

try{
// Add your complete portion of code here //
System.out.println("Portion of code executed Successfully");
}
catch(Exception name)
{
System.out.println("Portion of code failed");
}
Please try and let me know.......

Related

How to move to ELSE condition if element is not visible in IF in selenium

I am writing a piece of code in which in the if condition I am giving a condition that if the element is displayed they only go to if part otherwise if the element is not displayed then it should go to else part. But whenever it is coming to the if condition, it searches for the element and when it doesn't find it, it gives a timeout exception. What can be done ?
public void addaddress() {
suites.setupEnviroment();
WebDriver driver = suites.getWebDriver();
try {
//code to find elements
try {
if(driver.findElement(By.xpath("//div[#class='toast lgksToast ']")).isDisplayed()){
System.out.println("fail");
}
else{
System.out.println("pass");
}
} catch (Exception e) {
System.out.println(e);
}
}catch(Exception e) {
System.out.println(e);
}
}
In the above code if element with this xpath (//div[#class='toast lgksToast ']) is not found then its not executing else part
what should i do for thid please suggest.
Thanks in advance
Use the size() method with findElements and it will start working.
if(driver.findElements(By.xpath("//div[#class='toast lgksToast ']")).size() > 0) {
System.out.println("fail");
} else {
System.out.println("pass");
}

How Selenium getPageSource() work when we use switchTowindow is used?

What driver.getPageSource() method return if I switch the driver to some other window i have checked it is returning me the page source of the first page i.e. the first webpage I have launched how to get page source of current switched window..without relaunching the page....??
I have written the code like this I am successfully switching to the new window..but unable to get page source of current window...
public boolean switchToWindow(String title)
{
Set<String> availableWindows = webDr.getWindowHandles();
if (availableWindows.size() > 1)
{
try
{
for (String windowId : availableWindows)
{
if(webDr.switchTo().window(windowId).getTitle().equals(title))
{
return true;
}
}
} catch (Exception e) {
logger.handleError("No child window is available to switch ", e);
}
}
return false;
}
driver.getPageSource() should return the current active window source. From your code you can call driver.getPageSource() after switching to window.
public boolean switchToWindow(String title)
{
Set<String> availableWindows = webDr.getWindowHandles();
if (availableWindows.size() > 1)
{
try
{
for (String windowId : availableWindows)
{
if(webDr.switchTo().window(windowId).getTitle().equals(title))
{
System.out.println(driver.getPageSource());
return true;
}
}
} catch (Exception e) {
logger.handleError("No child window is available to switch ", e);
}
}
return false;
}

Not all code paths return value while using Try Catch

I have been getting "not all code paths return value" in the following code. I have the code below. I think I am returning appropriately but still there is an error.
[Route("User")]
public HttpResponseMessage Post([FromBody] Employee employee)
//FromBody forces the web api to read a simple tye from the request body.
{
try
{
Employee incomingEmployee = employee;
if (incomingEmployee == null)
{
Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Could not read the request");
}
else if (UserManager.AddUser(employee) > 0)
{
return Request.CreateResponse(HttpStatusCode.Created);
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Could not save to database");
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
You forgot a return statement in the first if statement.
[Route("User")]
public HttpResponseMessage Post([FromBody] Employee employee)
//FromBody forces the web api to read a simple tye from the request body.
{
try
{
Employee incomingEmployee = employee;
if (incomingEmployee == null)
{
-->return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Could not read the request");
}
else if (UserManager.AddUser(employee) > 0)
{
return Request.CreateResponse(HttpStatusCode.Created);
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Could not save to database");
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}

Not able Scan using redis template

I am trying to use SCAN http://redis.io/commands/scan to iterate over all the keys present in redis. But the Redis template provided by spring do not have any scan() method. Is there any trick to use the above?
Thanks
You can use a RedisCallback on RedisOperations to do so.
redisTemplate.execute(new RedisCallback<Iterable<byte[]>>() {
#Override
public Iterable<byte[]> doInRedis(RedisConnection connection) throws DataAccessException {
List<byte[]> binaryKeys = new ArrayList<byte[]>();
Cursor<byte[]> cursor = connection.scan(ScanOptions.NONE);
while (cursor.hasNext()) {
binaryKeys.add(cursor.next());
}
try {
cursor.close();
} catch (IOException e) {
// do something meaningful
}
return binaryKeys;
}
});
Set<String> keys = (Set<String>) redisTemplate.execute((RedisCallback<Set<String>>) connection -> {
Cursor<byte[]> cursor = null;
Set<String> keysTmp = new HashSet<>();
try {
cursor = connection.scan(new ScanOptions.ScanOptionsBuilder().match(keyPrefix + "*").count(10000).build());
while (cursor.hasNext()) {
keysTmp.add(new String(cursor.next()));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (Objects.nonNull(cursor) && !cursor.isClosed()) {
try {
cursor.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return keysTmp;
});

How to check if a new window is loaded successfully?

I have to access all the anchors on a specific div. Then, I have to assert if
the links are opened in a new window and
also make sure that the link is not broken.
How can this be done?
use findbyelements to collect list of links. Put them into a loop and select a link. then use "getWindowHandle" to switch to new window where an assertion can be implemented that "Page Doesn;t exist" or some other error message not displayed. This will ensure whether a link is broken
I used the following methods to verify if the links are opening a new window and are not broken. Code comments explains the code.
public boolean xAnchors()
{
String parentHandle = driver.getWindowHandle(); // get the current window handle
// System.out.println(parentHandle);
boolean isValidated = true;
try{
List<WebElement> anchors = wait.until(ExpectedConditions.visibilityOfAllElements(driver.findElements(By.xpath("//div[#class='container-with-shadow']//a")))); // This is an array of anchor elements
try
{
for (WebElement anchor : anchors){ //Iterating with the anchor elements
String anchorURL = anchor.getAttribute("href");
anchor.click();
String newWindow ="";
for (String winHandle : driver.getWindowHandles()) {
// System.out.println(winHandle);
driver.switchTo().window(winHandle); // switch focus to the new window
newWindow = winHandle; //Saving the new window handle
}
//code to do something on new window
if(newWindow == parentHandle) //Checking if new window pop is actually displayed to the user.
{
isValidated = false;
break;
}
else
{
boolean linkWorking = verifyLinkActive(anchorURL); //Verifying if the link is Broken or not
if(linkWorking)
{
System.out.println("The anchor opens a new window and the link is not broken");
isValidated = true;
}
else
{
System.out.println("The anchor either does not open a new window or the link is broken");
isValidated = false;
}
}
driver.close(); // close newly opened window when done with it
driver.switchTo().window(parentHandle); // switch back to the original window
}
}
catch(Exception e)
{
isValidated = false;
}
}
catch(Exception e)
{
System.out.println("No Anchors founds on this page.");
isValidated = true;
}
System.out.println(isValidated);
return isValidated;
}
public boolean verifyLinkActive(String linkUrl){
try {
URL url = new URL(linkUrl);
HttpURLConnection httpURLConnect=(HttpURLConnection)url.openConnection();
httpURLConnect.setConnectTimeout(3000);
httpURLConnect.setRequestMethod("GET");
httpURLConnect.connect();
if(httpURLConnect.getResponseCode()==HttpURLConnection.HTTP_NOT_FOUND){
System.out.println(linkUrl+" - "+httpURLConnect.getResponseMessage()
+ " - "+ HttpURLConnection.HTTP_NOT_FOUND);
return false;
}
else
{
return true;
}
} catch (MalformedURLException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}