Wednesday 12 December 2018

Reading csv files and comparing it

package selenium;

import java.util.ArrayList;
import java.util.HashMap;

public class CSVComparisonMain {

private static ArrayList<String> keys_Source=null;
private static ArrayList<String> keys_Destination = null;
private static HashMap<String, ArrayList> header_Values_Source;
private static HashMap<String, ArrayList> header_Values_Destination;

public static void main(String[] args) throws Exception
{
CSVFIleReader source_Obj = new CSVFIleReader("C:\\Avinash\\source.csv", "EVENT_CD");
source_Obj.readCSVFIle();
keys_Source = source_Obj.keys;
header_Values_Source = source_Obj.header_Values;


CSVFIleReader destination_Obj = new CSVFIleReader("C:\\Avinash\\Destination.csv", "EVENT_CD");
destination_Obj.readCSVFIle();
keys_Destination = destination_Obj.keys;
header_Values_Destination = destination_Obj.header_Values;

System.out.println("Comparison Starts.............!!!");


for (String key : keys_Source) {
if(header_Values_Destination.containsKey(key))
{
ArrayList source_Values =  header_Values_Source.get(key);
ArrayList destination_Values =  header_Values_Destination.get(key);
for (Object value : source_Values)
{
if(!destination_Values.contains(value))
{
throw new Exception("Source file Value: "+value+" is not matched in target file value: "+value);
}
}

}
else
{
throw new Exception ("Exception occured while comparing .csv file.......Key: "+ key +" not found in target file");
}
}
}

}


package selenium;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;

public class CSVFIleReader
{

BufferedReader csvReader = null;
String filePath = null;
String key = null;
public String delimiter = null;
int keyIndex = -1;

HashMap<String, ArrayList> header_Values = null;
ArrayList<String> keys =null;
ArrayList<String> values = null;

public CSVFIleReader(String filePath , String key)
{
this.filePath = filePath;
this.key = key;
header_Values = new HashMap<>();
keys = new ArrayList<>();
values = new ArrayList<>();
}


public void readCSVFIle()
{
String line = null;
int header = 0;
try
{
csvReader = new BufferedReader(new FileReader(filePath));
while((line=csvReader.readLine()) != null)
{
String delimit = getDelimiter(line);
System.out.println(line);
if(delimit != null)
{
++header;
generateKeyValuePair(line,header);
}
}
printCSVFile();
csvReader.close();
csvReader = null;
}
catch(Exception e)
{

}
}


public void generateKeyValuePair(String line, int header)
{
ArrayList<String> values = new ArrayList<>();
try
{
if(delimiter.equalsIgnoreCase("pipe") || delimiter.equalsIgnoreCase("comma"))
{
String[] words = line.split("\\|");
if(words.length > 1)
{
for (String value : words)
{
values.add(value);
}
}
if(words.length <= 1)
{
words = line.split("\\,");
if(words.length > 1 )
{
for (String value : words)
{
values.add(value);
}
}
else
throw new Exception("Exception occured while parsing .csv file. Delilmiter is not valid");
}
else
{
throw new Exception("Exception occured while parsing .csv file. Delilmiter is not valid");
}
if(header == 1) //It Means first line is header
{
if(values.contains(key))
{
keyIndex = values.indexOf(key);
}
}

keys.add(values.get(keyIndex));
header_Values.put(values.get(keyIndex).toString(), values);


}
}
catch(Exception e)
{
System.out.println(e.getMessage());
System.exit(0);
}
}

public String getDelimiter(String line)
{
String words[]  = line.split("//|");
if(words.length>0)
{
delimiter = "pipe";
}
else
{
words = line.split("//,");
if(words.length > 0)
{
delimiter = "comma";
}
}
return delimiter;
}

public void printCSVFile()
{
Set<Entry<String, ArrayList>> entrySet = header_Values.entrySet();
for (Entry<String, ArrayList> entry : entrySet)
{
System.out.print(entry.getKey() );
ArrayList values = entry.getValue();
for (Object value : values) {
System.out.print("         "+value.toString());

}
System.out.println();
}
}


public static void main(String[] args)
{
CSVFIleReader obj = new CSVFIleReader("C:\\Avinash\\Temp.csv", "EVENT_CD");
obj.readCSVFIle();

}

}







Saturday 11 August 2018

Handling multiple windows in selenium

Handling Window Pop Up In Selenium: 

There may be a situation while doing automation where we need to handle multiple window popup or where we need to go to appropriate window among multiple windows at run time. Selenium code /automation get focused on default/parent window.
E.g If you navigate or go to Naukri.com url then you will get multiple window pop up only when if you haven't disable pop up option.

Here, How do we know that it is a window popup or java script pop up or Jquery/Normal pop up.

Window Pop up:

           Window pop up has minimize, maximize and close button like any normal browser has.
            driver.switchTo().window("windowName);
            driver.switchTo().window();
         
           Here driver referes to webDriver object -

           WebDriver driver = new ChromeDriver();

Java Script Pop Up: 

           Java script pop up doesn't have minimize or maximize button/option also focus is only on java script pop up page. you can't ignore the java script popup but window pop up you can ignore it and perform operation on any other windows.

Ways to Handle Window Pop Up in Selenium:
    
           Selenium webdriver assign unique id (alpha numeric ) to every window to identify uniquely. The alpha numeric id (unique id) is called "Window Handle" in selenium.

How to get Window Handle:

          String handle = driver.getWindowHandle();

If there are multiple window gets opened when you click on any link,button etc... then to get "window Handle" of each window -

          Set<String> windowHandles = driver.getWindowHandles();

"getWindowHandles()" : method return window handle (unique id for each opened window) so that the return type is set. Because set will not contain duplicate elements so here getWindowHandles return unique id/window handles for each winodw and stored in Set.

How to switch to correct / appropriate window:

          Basically there are two ways to switch to appropriate window.

  1. By using windowName
         driver.switchTo().window( "windowName" );
        or
     
     2.  To get current/parent/default window handle:

        String handle = driver.getWindowHandle();
        driver.switchTo().window( handle  );

        or

        Set < String > windowHandles = driver.getWindowHandles();
        for(String handle : windowHandles )
         {
             driver.swicthTo().window( handle ); 
        }


Example:





Sunday 24 June 2018

Spinner To handle in Selenium











Firstname Lastname Age Select
Jill Smith 50
Eve Jackson 94
John Doe 80

Handling Spinner in Selenium

Handling Spinner In Selenium:

       To handle Spinner in selenium we have to use Synchronization concept with the help of wait.
It is always best to use Explicit Wait  on each control. so we have been  using Explicit Wait in our below example.

We are handling Spinner from  Spinner Link  this link. Click on it.

Basically above link contains two buttons-
1- Show Spinner
2- Hide Spinner

Show Spinner: When we click "Show Spinner" button then spinner is moving with 5-second timeout once 5-Second elapsed data will be loaded in tabular format.

Hide Spinner: When we click on "Hide Spinner" button It will hide the Spinner as well as tabular data (if tabular data is present/already loaded on page)

Intention of having such scenario/example is correlating with real time scenario- where when user click on any button then data is fetching from database in mean time spinner is running on page and  block the page activity once the data is ready spinner will disappear from screen.


Explicit Wait:
  1. WebdriverWait
  2. FluentWait
In below example we have used fluent wait with Function which is parameter to until function.
In example we have passed Webdriver object and By class object which is the locator path to spinner to function - waitTillSpinnerDisable(WebDriver driver, By by)

apply(): We have override apply method which will return either true or false. In example  it will return TRUE  in case of spinner is disappear (i.e. style.display="none") else it will return FALSE in case of timeout or style.display="block".

Once the Spinner is disappear it will load the data in tabular format and we have to parse the table where we need to select check on the basis of if  Name & Surname gets matched with tabular data where we passed Name & Surname at  execution time.


Execution Steps:
  1. Load the page
  2. Click on Show Spinner button
  3. Pass the driver object and locator for Spinner to waitTillSpinnerDisappear method
  4. Check the method return type if above method waitTillSpinnerDisappear return true then
  5. Parse the table with condition Name & Surname gets matched if match then select respective check box.
Download:

Download Spinner.html file form below link :- 


or 

Refer to page- 




Java Code:


Sunday 17 June 2018

Handling Dynamic Web Tables Using Selenium


Handling Dynamic Web Tables Using Selenium by using XPATH

     In below example we have consider Application Under Test from url as- https://www.redmine.org/issues . 
Where this url/application contains issues reported by users etc.. All the reported issues are in 
tabular format. In below example we have used xpath with multiple condition in a single xpath.
Also we have passed java variable as a argument to xpath at runtime.
        Here, we have to pass issueId and status as a argument below code will check issueId and respective 
status code is matched or not with table data if not it will click on next page and searched 
the given condition with table data it will search until it will find at least one of the record. 
Once the record found then execution will stop.


Screenshot of the Page:


Java Code:

package seleniumCode;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class WebTable 
{
 public static void main(String[] args) 
  {
     WebDriver driver = null;  
     List<WebElement> listWebElement = null;
     boolean flag = false;
  
    driver = new FirefoxDriver();
    driver.manage().window().maximize();
    driver.get("https://www.redmine.org/issues");
    
    String issueId = "28232";
    String status = "New";
  
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

    do
     {   
 listWebElement = driver.findElements(By.xpath("//table[@class='list issues']
          //tr//a[text()='"+issueId+"']//ancestor::td//following-sibling::
         td[text()='"+status+"']//preceding-sibling::td/input"));
   
 for (WebElement element : listWebElement) 
 {
  System.out.println(element.getAttribute("value"));
  element.click();
  flag = true;
  break;
 }
  
 if(flag==true)
   break;
 if(flag == false || listWebElement.size()==0)
  {
    //Page Down
    Actions ac = new Actions(driver);
    ac.moveToElement(driver.findElement(By.cssSelector("a.atom"))).build().perform();
    try 
             {
  Thread.sleep(2000);
       } 
           catch (InterruptedException e) 
            {
       // TODO Auto-generated catch block
  e.printStackTrace();
     }    
    
     driver.findElements(By.cssSelector("a.next")).get(0).click();
 }
  
      }while(driver.findElements(By.cssSelector("a.next")).size()>0 || flag==false);
   } 
 
}




References:  https://www.redmine.org/issues

See Also: