Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Sunday, April 10, 2016

Regular expressions in test automation

In many of the test scenarios, we need to validate the UI text where the text or partial of it is dynamic. In such cases, we need to use regular expressions to validate the text. Below are few example which can help you.

Example - 1
Suppose you want to validate a pattern 'CHICAGO, IL 60603 (1 mi)'. Where 'CHICAGO, IL' is the location and it follows with a zip and in braces single digit indicating distance in miles. If in this string the location string is as per the preferences or settings that you have made in your application and other part of the string you need to validate, you can write a regular expression as below:
public static boolean validateLocation(String location, 
                             String locationWithZipAndDistance) {
 String locationPattern = location + " [0-9]{5} \\([0-9]{1} mi\\)";
 // e.g. CHICAGO, IL 60603 (1 mi)
 // where value of 'location' is 'CHICAGO, IL'
 Pattern pattern = Pattern.compile(locationPattern, Pattern.CASE_INSENSITIVE);
 Matcher matcher = pattern.matcher(locationWithZipAndDistance);
 return matcher.matches();
}
Usage:
String searchLocation = "CHICAGO, IL 60603 (1 mi)";
String location = "CHICAGO, IL";
System.out.println(validateLocation(searchLocation, location));// output: true
In the above example it will return true if the input string is in either case as it has compiled with CASE_INSENSITIVE pattern.

Example - 2
If you want to validate a phone number text in the UI with a certain format, for example '(866) 825-3227' then you can use below regular expression
public static boolean validatePhone(String phone) {
 String phonePattern = "\\([0-9]{3}\\) [0-9]{3}\\-[0-9]{4}";
 // e.g. (866) 825-3227
 Pattern pattern = Pattern.compile(phonePattern);
 Matcher matcher = pattern.matcher(phone);
 return matcher.matches();
}
Usage:
String ph = "(866) 825-3227";
System.out.println(validatePhone(ph));// output: true
Example-3
Lets assume you are validating some string with days and time, example 'Mon - Fri: 7:00 AM - 6:30 PM', you can use the regular expression in the following way
public static boolean validateOfficehours(String officeHours) {
 String officeHourPattern = "(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat) - (?:Sun|Mon|Tue|Wed|Thu|Fri|Sat): (?:([0-9]{1,2}:[0-9]{2} (?:AM|PM) - [0-9]{1,2}:[0-9]{2} (?:AM|PM))|Closed)";
 // e.g. Mon - Fri: 7:00 AM - 6:30 PM
 // e.g. Sat - Sun: Closed
 Pattern pattern = Pattern.compile(officeHourPattern);
 Matcher matcher = pattern.matcher(officeHours);
 return matcher.matches();
}
Usage:
String officeHoursWeekday = "Mon - Fri: 7:00 AM - 6:30 PM";
String officeHoursWeekend = "Sat - Sun: Closed";
System.out.println(validateOfficehours(officeHoursWeekday));// output: true
System.out.println(validateOfficehours(officeHoursWeekend));// output: true
These are very basic scenarios, using these you can validate maximum of the dynamic texts. Feel free to ask me if you face any different scenarios which need my help.
For more information, please refer here and also you can check the Pattern class for other available functionalities.

Friday, May 16, 2014

Array to List and List to Array in Java

While testing web applications we came across many list of elements or an element with list of data. In such cases we may need the following conversation instead of iterating over an array or a list.
 
Please refer the below simple example to convert a string array to a list and vice versa. But be careful about the order of elements, If required you may use collection methods to do so.

Lets take an arry of strings as below
String[] elementsAsArray = new String[]{"ele1","ele2","ele3"};

Array to List:
List arrayAsList = Arrays.asList(elementsAsArray);

List to Array:
String[] listAsArray = arrayAsList.toArray(new String[arrayAsList.size()]);

Saturday, December 21, 2013

Format string for locators

There are many locators for web elements which are of same kind, only they vary with a small difference in index or string such as 
"//div[@id='one']/span[text()='jack']" and 
"//div[@id='one']/span[text()='john']"

For these web elements we should find a common locator with an input span text.
Let's take an example of a web element,
  1. Coffee
  2. Tea
  3. Milk
  4. Soup
  5. Soft Drinks
The locator for the above list items 'Soft Drinks' can be represented as below:
private final String DRINK_ITEM = "ul#drinks li:nth-of-type(5)";// using CSS selector
or
private final String DRINK_ITEM = "//ul[@id='drinks']/li[5]";// using Xpath
For finding 5th 'li' item we can directly use the above locator, but when we want to use 2nd 'li' item or some other item or all 'li' items at a time, then we need to represent the locator in a common way.
  • By direct use: 
For a list item,
WebElement element= driver.findElement(By.xpath(DRINK_ITEM));
element.doSomething();
Or, for all list items,
for (int i = 1; i < count; i++) {
 WebElement element = driver.findElement(By.xpath("//ul[@id='drinks']/li[" + i + "]"));
 element.doSomething();
}
  • By formatting the locator:
For a list item,
String drinkItem = String.format(DRINK_ITEM, 5);
WebElement element = driver.findElement(By.xpath(drinkItem));
element.doSomething();
For multiple list items,
for (int i = 1; i < count; i++) {
 String drinkItem = String.format(DRINK_ITEM, i);
 WebElement element = driver.findElement(By.xpath(drinkItem));
 element.doSomething();
}
If you are still not clear about how to use format string, please see the below examples:
private final String GRID_TABLE_VIEW = "div#panel2content div.table.%s";
private final String RESULT_TABLE_VIEW = "//div[@id='panel1content']//div[%d]/span[text()='%s']";
private final String SPACE_TOGGLE_MENU_OPTION = "ul#spacing_toggle li:nth-of-type(%d)";

String gridTableView = String.format(GRID_TABLE_VIEW, "filterByName");
String resultTableView = String.format(RESULT_TABLE_VIEW, 2, "bill");
String spaceToggleMenuOption = String.format(SPACE_TOGGLE_MENU_OPTION, 3);

/** It will print "div#panel2content div.table.filterByName" */
System.out.println(gridTableView);

/** It will print "//div[@id='panel1content']//div[2]/span[text()='bill']" */
System.out.println(resultTableView);

/** It will print "ul#spacing_toggle li:nth-of-type(3)" */
System.out.println(spaceToggleMenuOption);

Tuesday, December 06, 2011

Logging using java.util.logging.Logger (Custom logging)

Sometimes in our application we need to log different messages like info,warning,error etc.Here i have given a way how we can use it in our application.
Following 'Log' class creates different log files taking different logger value by input and it also maintains the directory structure of log files according to the value of 'path'  passed to the constructor of 'Log' class.For example, if we 'll pass a parameter 'utils.Example',it will create a file 'logs/utils/Example.log' in the current directory.
Note:First it checks for the directory 'logs/utils' is present or not if it is not present it creates the directory.

//Log.java
  1. package utils;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.util.logging.FileHandler;
  5. import java.util.logging.Logger;
  6. import java.util.logging.SimpleFormatter;
  7.  
  8. public class Log {
  9.  
  10.   static FileHandler handler;
  11.   static Logger logger;
  12.  
  13.   public static void createLog(String path){
  14.     try {
  15.       String [] s = path.split("\\.");
  16.       File f = new File("./"+"logs/"+s[s.length-2]);
  17.       if(f.exists()==false){
  18.         f.mkdirs();
  19.       }
  20.       handler = new FileHandler("logs/"+s[s.length-2]+"/"+s[s.length-1]+".log");
  21.       handler.setFormatter(new SimpleFormatter());
  22.       logger = Logger.getLogger(path);
  23.       logger.addHandler(handler);
  24.      } catch (IOException e) {
  25.         e.printStackTrace();
  26.      }
  27.   }
  28.  
  29.   public static void loggerINFO(String msg){
  30.      logger.info(msg);
  31.   }
  32.  
  33.   public static void loggerWARN(String msg){
  34.      logger.warning(msg);
  35.   }
  36.  
  37.   public static void loggerERROR(String msg){
  38.      logger.severe(msg);
  39.   }
  40. }
//Example.java
  1. package utils;
  2. import static utils.Log.loggerINFO;
  3. import static utils.Log.loggerWARN;
  4. import static utils.Log.loggerERROR;
  5.  
  6. public class Example {
  7.  
  8.    public Example() {
  9.      Log.createLog(this.getClass().getName());
  10.    }
  11.  
  12.    public void method1(){
  13.      loggerINFO("Doing division by zero");//Log an INFO message
  14.      loggerWARN("May get ArithmeticException");//Log a WARNING message
  15.      try {
  16.        int i = 20/0;
  17.      } catch (Exception e) {
  18.        loggerERROR(e.getMessage());//Log a SEVERE message
  19.      }
  20.    }
  21.  
  22.    public static void main(String[] args) {
  23.      new Example().method1();
  24.    }
  25. }
After running this we 'll get a log file 'logs/utils/Example.log' (In eclipse,if 'Example.java' is in 'utils' package ,you 'll find a log file 'Example.log' in the 'logs' folder which is generated parallel to 'src' folder of the current project)
Note: Everytime you run the 'utils/Example.java' you 'll get a fresh file with new content.

//Content of 'logs/utils/Example.log' after running 'utils/Example.java'

Dec 6, 2011 6:37:33 PM utils.Log loggerINFO
INFO: Doing division by zero
Dec 6, 2011 6:37:33 PM utils.Log loggerWARN
WARNING: May get ArithmeticException
Dec 6, 2011 6:37:33 PM utils.Log loggerERROR
SEVERE: / by zero

Reading and Writing a Properties File

The following code shows how to read and write properties file. With getProperty(key) method we can get the property value by passing property key and like that way with setProperty(key,value) we can set given value to the specified property.

// Read properties file.
  1. Properties properties = new Properties();
  2. try {
  3.     properties.load(new FileInputStream("filename.properties"));
  4.     String s= prproperties.getProperty("Key1");
  5.     System.out.println(s); //Value1
  6. } catch (IOException e) {
  7.     e.printStackTrace();
  8. }
// Write properties file.
  1. try {
  2.     prproperties.setProperty("Key1""ValueXxx");
  3.     properties.store(new FileOutputStream("filename.properties")null);
  4. } catch (IOException e) {
  5.     e.printStackTrace();
  6. }
//filename.properties before write
  1. Key1=Value1
  2. Key2=Value2
  3. Key3=Value3
//filename.properties after write
  1. Key1=ValueXxx
  2. Key2=Value2
  3. Key3=Value3

Renaming a File or Directory

The following code will rename the file/directory.Here 'FileOrDirNameBefore' is the directory name to be renamed to 'FileOrDirNameAfter'.
  1. File f1= new File("FileOrDirNameBefore");
  2. File f2= new File("FileOrDirNameAfter");
  3. boolean success = f1.renameTo(f2);
  4. if (!success) {
  5.     // File was not successfully renamed
  6. }

Tuesday, November 08, 2011

Create file and overwrite if it exists

The following code 'll delete the file 'myfile.html' if exists and 'll create a new file 'myfile.html'
  1. File f = new File("myfile.html");
  2. if(f.exists()){
  3. f.delete();
  4. f.createNewFile();
  5. }

Create file if it does not exist

The following code 'll create a file 'examplefile.txt',if doesn't exist
  1. try {
  2.  File file = new File("examplefile.txt");
  3.  // Create file if it does not exist
  4.  boolean success = file.createNewFile();
  5.  if (success) {
  6.  // File did not exist and was created
  7.  } else {
  8.  // File already exists
  9.  }
  10. } catch (IOException e) {
  11. e.printStackTrace();
  12. }