Results for Selenium

How To Handle Keyboard and Mouse Operation In Selenium Via Action class?

June 30, 2017
Keyboard and Mouse operations are two integral part of any application. More the reach UI more the complex operation. Here is a list of methods of action classe that is supported by Selenium in order to handle Mouse and Keyboard operations.

Keyboard Operations:

Operation         Syntax Usage
KeyBoard         sendkeys() It sends the string to the locator
keyDown(keys modifier) Takes the modifier key(shift,alt,control) as parameter and modifies the key keys.SHIFT
keys.ALT
keys.CONTROL
The exception generated is IllegalArgumentException
keyDown(WebElement element,keys modifierKey) Another flavor of the keyDown which the modifier key press action is performed on a webElement. 
keyUp It is used to simulate the modifier key up or key release action. This methods needs to be invoked after a keyDown method
keyUp(WebElement element,keys modifierKey) Another flavor of the keyUp which the modifier key release action is performed on a webElement. 
sendKeys(CharacterSequence keysToSend) It is used when we need to send sequence of keys to a currently focused webElement. It is helpful when using modifier keys and that can not be released on the element.
sendKeys(WebElement element,CharacterSequence keysToSend) Sends a sequence of keys to a webElement.
WebElement textbox=driver.findElement(By.locator_of_textbox);
Action builder=new Action(driver);
Action typeInCAPS=builder.keyDown(textbox,keys.SHIFT);
                         .sendkeys(textbox,"abc");
                         .keyup(textbox,keys.SHIFT);
                         .build();
typeInCAPS.perform();







Mouse operations:
Operation         Syntax Usage
Mouse         Click() It clicks on the current mouse pointer Best when used with mouse and keyboard events. Mostly a composite events
Click(WebElement element) It clicks on the middle of the webelement that is passed as a parameter.
ClickAndHold() Performs a click method without releasing the mouse button 
ClickAndHold(WebElement element) It is used to Performs a click method without releasing the mouse button on a webelement
ContextClick() Performs a right click operation in the current location of the mouse.
ContextClick(WebElement element) Performs a right click operation in the current location of the mouse on an element.
doubleClick() Performs a double click operation in the current location of the mouse.
doubleClick(WebElement element) Performs a double click operation in the current location of the mouse on an element.
dragAndDrop(WebElement fromElement,WebElement toElement) Performs a drag and drop method from one element to other.
dragAndDropBy(WebElement fromElement, xoffset,int yoffset) performs drag and drop from element to a x,y position Clicks on the webelement and drag to the x,y location and drops it
moveByOffset(int xoffset,int yoffset) Performs a move operation of the mouse pointer based on x and y
moveToElement(WebElement toElement) Performs a move operation to the webelement, 
moveToElement(WebElement element,int xoffset,int yoffset) Performs a right click operation in the current location of the mouse on an element. x,y calculation is done from the top left corner of the webelemnt specified.
release() Releases the pressed left mouse button at the current mouse position.
release(WebElement element) Releases the pressed left mouse button to an webelement
build() Generates the composite action
WebElement rtClickElement=driver.findElement(By.locator_of_element);
Action rightClick=new Action(driver).contextClick(rtClickElement);
rightClick.build().perform()

one more example can be as follows

WebElement fromElement=driver.findElement(By.locator_of_fromElement);
WebElement toElement=driver.findElement(By.locator_of_toElement);
Action builder=new Action(driver)
Action dragAndDrop=builder.clickAndHold(fromElement)
                          .moveToElement(toElement)
                          .release(toElement)
                          .build();
dragAndDrop.perform();

Last item in this category is to discuss the Drag and Drop. With rich web interface,drag able web elements are very common now a days.Using Action class (an interface which represents a single user interaction) we can simulate the same thing while testing.




How To Handle Keyboard and Mouse Operation In Selenium Via Action class? How To Handle Keyboard and Mouse Operation In Selenium Via Action class? Reviewed by Animesh Chatterjee on June 30, 2017 Rating: 5

How To Handle Sequence Error with @ Test Annotation in TestNG

September 04, 2016
While using TestNG framework, we provide @Test annotation for original test method.
Example:
public class Test1 {
  @Test
  public void testMethod1() {
  }
}


So the code says that testMethod1() is a function and since it is annotated with @Test so it will execute.

Problem starts when we have multiple functions to be covered as a part of the test.
@Test
  public void testMethodForRefresh()
  {
         System.out.println("Refresh the page");
  }
 @Test
  public void testMethofForClick()
  {
         System.out.println("Click on a link");
  }

our objective is  to Refresh a page and click on a link. Accordingly we have coded. But when you will execute the tetstcases, in the output, it is seen instead of Refresh method, Click method got executed first then Refresh method got executed.
Below are the ways how we can resolve this issue:

Process One:
TestNG follows the alphabetic order to pickup the methods when all the methods have same annotation as @Test. So name all your method accordingly..
Like - append Test00X in front of the methods. The first method what we need to call and execute will have name Test001_MethodForRefresh and next method will be Test002_MethofForClick


@Test
  public void Test001_MethodForRefresh()
  {
         System.out.println("Refresh the page");
  }
 @Test
  public void Test002_MethofForClick()
  {
         System.out.println("Click on a link");
  }


Process two:
A little more advanced upgrade is to set priority of the method. like: @Test(Priority=1). In this way, we don't have to change the method name.

@Test (Priority=1)
  public void testMethodForRefresh()
  {
         System.out.println("Refresh the page");
  }
 @Test(Priority=2)
  public void testMethofForClick()
  {
         System.out.println("Click on a link");
  }

Process three:
This is another approach weher we need to mention the sequence in testng.xml or pom.xml.
documentation for @Test is available here: http://testng.org/doc/documentation-main.html




How To Handle Sequence Error with @ Test Annotation in TestNG How To Handle Sequence Error with @ Test Annotation in TestNG Reviewed by Animesh Chatterjee on September 04, 2016 Rating: 5

Top Ten Strategies to Make Test Automation As a Service

May 08, 2016
Every journey towards automation  development is different from employees to employees and from companies to companies.Each one has some voice to venture.Some story to say. Some are good some are bad. Each story is unique.

Extensive testing before any release is not only necessary but also become essential for any company for their client and their clients's client,vendors,partners. Due to frequent change in IT industry,testcase base grows heavy in size. To run those huge cases,we need a strong manual team . Involvement of huge manual test engineers is nothing but loss human power.As they have to test the same test cases over and over for each release. Industry found out a common solution in the form of Automation testing. It is a sequence or series of actions performed by automation tool. The actions can or can not be dependent on human. During 2001 to 2005, the initial days of automation testing, automation team used to be a part of quality assurance or manual testing team.
A automation team was defined as a set of technology enthusiastic functional test engineers who writes VBA,or some small code base to make their job easy. Gone those days when team mainly used to depend on manual testing and automation was given a lower priority.

With the advancement of technology,languages, tools like automation,continuous integration,build and release team, VBscript, javascript ,Java,C# ,groovy, selenium, QTP, UFT, TOSCA,Silk automation testing took a greater stand in QA domain. Eventually during 2005 to 2010 unattended execution ,machine independent architecture , cross browser testing came to rescue development and QA. Slowly automation become a must go for any company's release cycle.Patch testing,Regression testing became very important for major players in software industry.The main purpose was to eliminate human related error from testing,speed up the execution and better ROI.

With the involvement of software design model like waterfall to v model to now days agile or rapid development ,automation becomes obvious. Agile and rapid development are meant to develop and change in a speedy way.So Automation needs to provide support in the same way.The nature of automation starts from unit testing to full execution, On demand execution to scheduled execution. Testing started rely on robot. Magnitude of testing is full day and night.When adopting such a huge speed, as a company, we need to adopt some strategies.
Here are the top ten strategies to make test automation as a service:

Must Read::Framework and Tool Evaluation  || Action Concept in QTP
1. When to use Automation:
Image Credit-http://www.snaptactix.com
Test Automation is a success in traditional way of testing in waterfall model, but a successful agile development can not really sustain without a good automated testing.
Go for automation testing if the project is long term and features will be tested again and again.Automation testing is only preferable if and only if the nature of testing is repeatable. Automation takes time to be mature but effective to catch bugs. It will give QA more confidence to look into the  non automated area.So use automation in such cases where-

  1. It saves time
  2. Increase accuracy
  3. Reduce cost
  4. Better ROI
  5. Better coverage
  6. Reusable
In agile when requirements may change every now and then, it is better to go for a TDD(Test Driven Development ) approach. This is surely ensure the proper and faster way of test development and execution.


2. Test Tool:

Image Credit https://www.qasource.com
Selection of the tool is very important as cost is associated with most of the tool.And Quality is associated with cost. Check for test tool compatibility with your UAT,the environment,browser.If Automation tool is compatible with your combination,half the battle is won. It is possible to test the environment in multiple language  along with normal testing.Once we get the correct tool for correct application , we will get more ROI.

Many a times, the tool sales person /team showcase their tool,in such  way, that the tool they are selling can automate everything a customer need. But reality is far from the show. So a expensive tool does not really make a functional team member an automation expert. Even they can not replace an automation expert.

Now the last aspect of tool selection could be o select some tool where your most of the knowledge base are. Simply if your resource is familiar to some technology or test tool or language, prefer the related tool.This will save time of initial learning and give automation a good start.

Test tool selection depends on the following factors:

  1. Affordability [Cost involves for this tool]
  2. Flexibility [How flexible the tool company about selling the tool or license]
  3. Compatibility [Can the tool support the UAT]
  4. Functionality[How easy the GUI or what feature the tool is offering]
  5. Usability[how easy to operate the tool]
  6. Maintainability [How easy to maintain the scripts]

If you are justifying a tool and not a member of management, please involve them from day one. And if you are a manager, please join the discussion to understand about the tool.If any team wants to get benefited with automation testing,management support is must. They must fund for R&D activities,pilot projects,fund for architecture development etc. Mostly it is top -down approach rather than a bottom up activity.

Must Read:: HTML Report in OATS::: HTML Report in QTP
3. Reporting:

Reporting should be the next major aspect of strategy. From the beginning, we need to standardize the reporting. Also we need to upgrade the reporting whenever necessary. Reporting should be customized or can be drilled to the lowest level. Creating various levels of abstraction is a very good approach.I like the jUnit/TestNG report for selenium. The consumers may be different for different level of reporting. Functional engineers may be drilling down till last level,Managers may be interested about how many scripts,how many pass etc. Top management may be looking at overall percentages.
Always tailor automation and information to meet automation objectives.
Must Read:: Top 12 framework Features:::Top 10 Framework Features
4. Framework:

We need to design a structured approach by which automation test engineers can produce maximum testcases by providing minimum efforts. We need to ensure maximum performance.Prepare best practices . Best would be to adopt a modular approach. Better to use a library driven approach rather putting everything in a script. Decomposition of the flow should be based on independent tasks. Not on the basis of  a big flow. The independent task lets call Units should have only one trigger point and only one outcome. With these units, one can make flows.
Always create layer of framework. The top layer should be a simple script with simple English. GEB and SPOC are very popular in this aspect. The test inventory should be very user friendly to a non technical user.
There are many IDEs(Integrated development environment) available in the market.One should design the framework such a way that it can overcome the limitation of the tool's GUI Part.
So framework development is not only a conceptual thing. There are finance area also attached to it. Be very careful to understand the requirements,tool selections and hiring.
5. Test Script:

Test script should be independent but structured. Each test case should be easy maintainable.Follow Hermetic Test Pattern  for test development. Even now single ton approach is also nice.Test cases should be accumulated in easy and random way. Functional team should set testcase as per their requirement.Decomposition of the flow should be based on independent tasks. Not on the basis of  a big flow. The independent task lets call Units should have only one trigger point and only one outcome. With these units, one can make flows.

Another way of automation is to check the heath of the test cases. And keep updating your inventory. The more we will test our testcases more we will get the quality. It will surely reduce  pesticide paradox in automation.

6. Clear Expectation:

Prepare a capability analysis of the engineers who are working in the team. second,prepare an estimation of the scripts according to the complexity[may be simple ,medium,complex,very complex]. Now set an target like in a day ,how many simple,medium,complex and very complex you can deliver.Estimate accordingly. I would suggest take 1-2 days buffer while planing and provide estimate accordingly.
Second important aspect is to get transparency. Yes. depending upon the maturity of the employees , we must be transparent to them. Information is power in our IT industry. In few cases, it is seen that the information is not shared to the team. Manager or lead poses to be over-smart thinks that this act gave them lot of power. Actually this is a poor managed team where actually nobody knows where the project stands.

7. Approach:

The best approach is to divide and rule approach. Look at your requirements then identify the smaller requirements. Now identify the smallest unit testcase that can be automated. Once this identification is done,look for reusable functions,common approaches. Build the helper functions. Then start automating with maximum re usability. In this way, many automation testcases can be automated within very short time.
Next to make test inventory scale-able and maintainable always depend on test data. Use testdata for triggering and running large scale testcase. There are many approaches to get or generate test data. But framework should support multiple format like-CSV,Spreadsheet,text file, random generation,xml. etc.Plug and play with these data source can give your test framework  wings.

Use different tools to understand the progress in milestone by milestone manner.Budget control,statistical tools like six sigma,lean,Failure analysis,Fish-bone, process control ,key performance indicators,regulars,Standardized reporting should be used to analysis different scenarios.
Retrospective meetings should be well prepared rather just jotting few points and go unprepared.
Every claim good or bad should be supported by supporting data.

8. Hiring:
In automation industry , we have two categories of test engineers.
1. Designer- Mainly Test Architect
2. Automator- Who will automate the test.

Automators are multi talented like a developer. They need to understand the requirements, create test case,create testscript,create supporting testdata, execute the test,analysis of the failures,re execution, reporting. So it is always better to have programming knowledge in automators.

How many engineers need to be hired depends on the load of work you will have. If the project follows waterfall model,you will get sometime to take a look of the work and estimate accordingly. But if the project follow a agile , then it is tough to get the projected load. So it is always better to have one or two shadow worker in buffer.Most of the companies now are creating talent pool.A pool of engineers with required skillset.

As I said earlier , It is no more a manual test engineer's job to automate application,It requires dedicated automation developer now a days. Apart from a dedicated team,the automation team requires a manager or a technical architect to drive the team. They should be from automation background. If the hiring is not correct way, like a manual test engineers given automation responsibilities or a manual manager is guiding automation team, then in most of the cases team lacks of motivation and innovation.

9. Operational Model:

As in agile methodology the load of the work is little unpredictable and requirements may get changed. As a result the traditional operative model of billing[Hours calculation,timesheet entry] may not work for both the vendor and client. In this changing moment of software development it may be good to go cloud's way of billing. Deliver the agreed quantity and get the billing. It is always a win win situation for both the parties as it follows pay as use mode. This solves the not used,un billable  resource problem. I have seen some model like the total no of scripts delivered, number of test execution happened,number of regression run,number of bugs logged.So according to your model,use quality center or jenkins to create more demand ,execution,daily execution,report to earn more.

Inside organization, follow different quality standard,documentation or CMMi level requirements.IT security,Data security,audit security,compulsory regulation,certification, quiz should be part of operation model. Employees should be encouraged to take the certifications,documentations,audit very seriously.

10.Do More with Automation:


Automation not only test your application but can do many more things. All tedious manual job like taking backup of the scripts,updating internal portal, posting report can be done with automation. I have heard one of the team automated the billing portal which was getting input data from review portal. I have experienced the automation of QC to OATS[Oracle Test Management] migration with the power of Selenium.
GUI testing is the mostly tested area in automation. But the success of GUI testing depends on many other factors. In my previous organization, in certain runs we have experienced 90% failures. While analyzing the failures we got to know that these were due to synchronization issue. Application was slow in nature. We use to give second round of execution of the failure testcases, and the 90% of them used to pass!!!.
After researching, we used direct database update,Seeded data and APIs to reduce the usage of GUI. That gave us speed of execution , less failure due to sync issues and more accurate bugs.
Well, more good was,we started supporting API testing as well.
Continuous Integration with automation testing is one of the prime factor for automation success.

These are the basic ten strategies that will surely support the TAAS. Let me know your views as well.








img credit-web.kalid.com.cn
Top Ten Strategies to Make Test Automation As a Service Top Ten Strategies to Make Test Automation As a Service Reviewed by Animesh on May 08, 2016 Rating: 5

How To Take ScreenShot in Selenium in Three Quick Ways

March 30, 2016
Hope you enjoyed my last post on how to get webElement count. Now with this post, I am going to write a code that will take screenshot with Selenium.It is not something new.It is already there in different websites. I am just compiling these into one post and that is as per normal basic framework.
So to start with I will assume, there is a small framework in place. That is the driver class which will have all the methods. For advance stuff,we might have a separate helper class too.
So lets get started:
The first approach: Using TakesScreenshot
public void getscreenshot() throws Exception 
     {
             File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
             FileUtils.copyFile(scrFile, new File("<<path with name of the file>>"));
     }
The second Approach: We will have a overloaded methods of takingscreenshot where it takes no parameter or one parameter which is the element.Also there are two ways to implement it. One is to give your element name and get the screenshot file as element name or set the file name with time stamp
public void takeSceenshot() throws IOException
 {
  TakesScreenshot oscn=(TakesScreenshot)driver;
  File oscnShot= oscn.getScreenshotAs(OutputType.FILE);
  File destfile=new File("D:\\My_projects\\Projects\\TestBase\\src\\Base\\Test.jpg");
  FileUtils.copyFile(oscnShot, destfile);
 }
 public void takeSceenshot(String elementType) throws IOException
 {
  TakesScreenshot oscn=(TakesScreenshot)driver;
  File oscnShot= oscn.getScreenshotAs(OutputType.FILE);
  File destfile=new File("D:\\My_projects\\Projects\\TestBase\\src\\Base\\Test"+elementType+".jpg");
  File destfile1=new File("D:\\My_projects\\Projects\\TestBase\\src\\Base\\Test"+GetTimeStampValue()+".jpg");
  FileUtils.copyFile(oscnShot, destfile);
  FileUtils.copyFile(oscnShot, destfile1);
 }
 public  String GetTimeStampValue()throws IOException{
     Calendar cal = Calendar.getInstance();       
     Date time=cal.getTime();
     String timestamp=time.toString();
     System.out.println(timestamp);
     String systime=timestamp.replace(":", "-");
     System.out.println(systime);
     return systime;
 }

Third Option could be:This using pure java with robot class.
protected void takeScreenShotMethod(){
     try{
         Thread.sleep(10000);
         long id = Thread.currentThread().getId();
         BufferedImage image = new Robot().createScreenCapture(new Rectangle(
             Toolkit.getDefaultToolkit().getScreenSize()));
         ImageIO.write(image, "jpg", new File("./"
             + id + "screenshot.jpg"));
     }
     catch( Exception e ) {
         e.printStackTrace();
     }
 }

I worked with these three ways to take screenshots.But mostly I like the second one. Now let us understand when we should use it. If the webpage is opening with some popup ,like rediff.com, or if in some cases webpage is minimized,It will take the screenshot of the webelement or the webpage even if new popups are opened.
But suppose you are using one application like desktop automation using selenium with a third party jars or applet automation, in that case we will go with third approach.
Do let me know if you agree or disagree with me.

How To Take ScreenShot in Selenium in Three Quick Ways How To Take ScreenShot in Selenium in Three Quick Ways Reviewed by Animesh Chatterjee on March 30, 2016 Rating: 5

How to Get All The Web Elements and Print Each Web Element Count In Selenium

March 28, 2016



In this post we will how to get all the webElements and how to get their numbers for each webelements.
I will be writing this as per very basic framework.So the precondition is a very basic framework is in place.Lets see how to code step by step to get the count of each type of elements.
Well,to start with let us make entry to a file from where my test will read the basic inputs like the browser,what to find[separated by "-"],url
url=http://www.rediff.com
Browser=FF
find=img-link

Now lets read this file from the driver class or base class:
public static  Properties readPropertiesFile() throws IOException
 {
  FileInputStream fs = new FileInputStream("D:\\My_projects\\Projects\\TestBase\\src\\Base\\Path.txt");
                 //need to change the path based on your file location
   properties= new Properties(System.getProperties());
  //Loading all the properties from Object Repository property file in to OR object
  properties.load(fs);
  return properties;
 }
Now we need to read properties one by one-so I will send the key to the getPropertiesFile function and it will return me the required value.
public String getPropertiesFile(String key) throws IOException
{
 allprops = readPropertiesFile();
 return (String) allprops.get(key);
}
Now once the reading is done, I need function that will drive the entire stuff like opening browser and navigate to url.It gose like-
public  void startupTest() throws IOException, InterruptedException {
 allprops = readPropertiesFile();
 String browserType=(String) allprops.get("Browser");
 String sURL=(String)allprops.getProperty("url");
 switch(browserType){
 case "FF":
 driver=initFirefoxDriver(sURL);
        //you may give IE,Chrome etc
 
 } 
As I may have given my browser type as IE,Firefox or chrome. So based on that I need to invoke the drivers.
private static WebDriver initFirefoxDriver(String sURL) throws InterruptedException {
  System.out.println("Launching Firefox browser..");
  WebDriver driver = new FirefoxDriver();
  driver.manage().window().maximize();
  driver.get(sURL);
  Thread.sleep(2000);
  
  return driver;
 }
Now,for calling this methods,I need a function with @before annotation as I will be driving this via jnit.
@Before
 public void startupTestForBase() {
  try {
   startupTest();

  } catch (Exception e) {
   System.out.println("Error....." + e.getStackTrace());
  }
 }
Well,now we need one more function to read the specific property files get get the count as per our need:

public int  ReturnElementCount(String setType)
 {   
  
  int counterofImage=0;
  List AllElements=driver.findElements(By.xpath("//"+setType));
  for(int i=0;i<AllElements.size();i++)
  counterofImage=counterofImage+1;
  return counterofImage;
 }
The whole code looks like-
package Base;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.Properties;

import org.junit.After;
import org.junit.Before;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;


public class BaseTest {
 public static Properties properties;
 private WebDriver driver;
 static Properties allprops;
 
  protected WebDriver getDriver() {
  return driver;
 }
public String getPropertiesFile(String key) throws IOException
{
 allprops = readPropertiesFile();
 return (String) allprops.get(key);
}
 
 public  void startupTest() throws IOException, InterruptedException {
 allprops = readPropertiesFile();
 String browserType=(String) allprops.get("Browser");
 String sURL=(String)allprops.getProperty("url");
 switch(browserType){
 case "FF":
 driver=initFirefoxDriver(sURL);
 
 }
 
 }
 @Before
 public void startupTestForBase() {
  try {
   startupTest();

  } catch (Exception e) {
   System.out.println("Error....." + e.getStackTrace());
  }
 }


 private static WebDriver initFirefoxDriver(String sURL) throws InterruptedException {
  System.out.println("Launching Firefox browser..");
  WebDriver driver = new FirefoxDriver();
  driver.manage().window().maximize();
  driver.get(sURL);
  Thread.sleep(2000);
  
  return driver;
 }
 public int  ReturnElementCount(String setType)
 {   
  
  int counterofImage=0;
  List AllElements=driver.findElements(By.xpath("//"+setType));
  for(int i=0;i<AllElements.size();i++)
  counterofImage=counterofImage+1;
  return counterofImage;
 }
 public static  Properties readPropertiesFile() throws IOException
 {
  FileInputStream fs = new FileInputStream("D:\\My_projects\\Projects\\TestBase\\src\\Base\\Path.txt");
  properties= new Properties(System.getProperties());
  //Loading all the properties from Object Repository property file in to OR object
  properties.load(fs);
  return properties;
 }
 @After
 public void teardown()
 {
  driver.quit();
 }
}
Now let us come to the actual testcase-
package Testcase;

import java.io.IOException;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import Base.BaseTest;

public class ReadingElements extends BaseTest {
 @Test
 public void getCountType() throws IOException
 {
  String type=getPropertiesFile("find");
  String[] set=type.split("-");
  for(String setType:set)
  {
   System.out.println("Count of "+setType+" is "+ReturnElementCount(setType));
  }
 }
 
}

Thats right!!! you can further encapsulate the things:
The output:
Launching Firefox browser..
Count of img is 128
Count of link is 3
There is a shortcut to get count. I have written it below:
public int  ReturnElementCount(String setType)
 {   
  
  
  return AllElements=driver.findElements(By.xpath("//"+setType)).size();
  
 }
 

How to Get All The Web Elements and Print Each Web Element Count In Selenium How to Get All The Web Elements and Print Each Web Element Count In Selenium Reviewed by Animesh Chatterjee on March 28, 2016 Rating: 5

Shall We Execute Our Automation Testcases in Random Order??

September 28, 2015
When I automate test cases, I always try to reuse what is already available in my test inventory. Always follow do not repeat yourself technique.  If atall components (functions, sub,procedure,testdata etc) are not matching with my requirement, I would create a new one.  Even there is a tendency to reuse the bunch of steps or bunch of tests even testsuite itself. Like me so many like minded persons available in information technology industry for sure.. :D

But as per testing best practice goes, we really need to improve our way of test development. As per that the best practice, we need to make test case independent to each other. There should not be any sharing between two test cases including test data.

Let us see with an example,what I am trying to venture through this post.

An example..
Lets say, I have to update a previously created employee who is attached to an organization.

So what are the manual testcase steps:
  • Create an Organization
  • Search for the same Organization and Create an Employee
  • Find the employee and find the organization and attach Employee to Organization
  • Now Update the same employee 

When I will automate the same flow I will create the structure like-

Testcase1: Create Organization
Testcase2: Create Employee
Testcase3: Attach Employee to Organization
Testcase4: Update Employee

Are test cases written in Big Ball of Mud test pattern correct?
With the advancement of testing,This is one of the basic test pattern where test assets are heavily shared between the test flows. Master driver or test suite can be also shared along with test data.There is no formal boundary or structure maintained to distinct between components[may be testdata,sub,macro,code etc]. Assume a scenario where a component of a test asset is reused by some hundred of test flows.Now to accommodate a new test case or a set of test cases we need to change the component a little bit. From the structural point of view as master drivers or test suites are shared,so we really do not know the impact of changing one component. With this approach it is very tough to find out which components use what all components.The change might fail some unnecessary test scripts in other area. So If we need to randomize the test cases designed in this pattern ,this might trigger failures. It will be needed for patchwork and workaround.So not so efficient way to execute them in random manner.

Are test cases written in spaghetti test pattern correct?
We will bunch these test cases into a batch called test suite and try to execute the same.
For this case we can simply put everything in a flow. Record playback like mechanism. Or we can divide the entire flow to sub flows[test cases] and stitch them. With this approach, each flow heavily dependent on the previous flow. As the state of the application is used by the next test case,so we can not run them individually. They are tightly coupled together. In such case the design pattern is spaghetti test pattern. So all test inventory which is having record playback framework and test cases  are tightly coupled ,we can not execute them in random order.

Are test cases written in Chain Linked test pattern correct?
Now where is Create Organization test case in inventory?? It is inside Organization module. Same like Create Employee will be inside Employee module and updating an employee may be in transaction or some other module. These type of approach where we will have different flows coming from different modules are upgraded from spaghetti test pattern.Each test case is considered as chain and bunch of chain hardly share the test data. But still it depends on the execution order to get the same state of application for the test cases.From the structure it is different from spaghetti model. Here the test cases are shared but the master driver or the test suite or the driver is independent of each other. Maintenance of this type of automation asset and  test data is a pain area for a organization. Mostly keyword driven framework, data driven framework, Modular decomposition approach,Function driven approach,Data oriented function driven approach follow chain linked test pattern. So randomize the test case execution may not suite for them.

The above three approaches talks about more re usability rather than independence of test cases.
 
public class updateEmployee{
@Test public void Create_Organization()
{
//Creation of org code goes here
}
@Test public void Create_Employee()
{
//Creation of Employee code goes here
}
@Test public void Update_Employee()
{
//Updating of Employee code goes here
}
}
With these kind of the approach the Test1 becomes the precondition for Test2 and Test1 and Test2 will both become precondition for Test3. These test cases can not be picked individually rather they needs to be run in a batch.

Advantages
  • No need to repeat the code.Optimum writing but maximum usage of test code
  • Structured or semi structured so finding out the batch and execute them is easy.
  • Mostly follows "do not repeat yourself" logic hence become modular with great ROI of automation.
  • Less execution time.

DisAdvantages
  • These type of test pattern mostly fail to give correct failure count.Or it is a constant pain for the test engineer to keep track. How? Let me explain... In the above test flow say Testcase-1[Create Organization] passed but Test Flow-2 [Employee Creation] failed. As Test case-1 and Test case-2 are precondition for Testcase-3 ,Hence Testcase-3 also will fail. or may not get executed depending upon your test configuration settings. So Report may look like Test-3 Passed-1 Failed-2. But no way, we can run these 2 failures. We need to execute 3 testcases once again. In an organization, in test inventory,thousands of scripts run.And if we consider ten parentage failures.We will have issues in reporting how much did we run really to get all test cases passed. Engineers need to be extremely careful to report
  • There is no way you can pick the failed test cases and execute them. As a result execution time becomes high. It becomes unreliable too
  • There is a huge chance that the polluted or corrupted test data may enter into next flow and may fail the flow.
Are test cases written in Hermetic test pattern correct?
Hermetic test pattern put more focus on test independence rather re usability. As per this test pattern each test case should be independent of each other. No sharing of test assets between test cases batched even in single test suite. Let us see how it will look like when we design our test cases as per Hermetic test pattern.
Test Name-CreateOrganization
 
public class CreateOrganization{
@precondition
//precondition steps go here
@Test 
public void Create_Organization()
{
//Creation of org code goes here
}
@Cleanup
//Cleanup code goes here ...here we delete all the test data created in the test. 
//Application goes back to original condition.
}


Test Name-CreateEmployee
 
public class CreateEmployee{
@precondition
public void Create_Organization()
{
//Organization Creation code goes here
//Create_Organization method of CreateOrganization testcase and 
//Create_Organization method of CreateEmployee testcase are different and has no link in between
}
@Test 
public void Create_Organization()
{
//Creation of org code goes here
}
@Cleanup
public void Delete_Organization()
{
//Cleanup code goes here ...here we delete all the test data created in the test. 
//Application goes back to original condition.
}
}

Test Name-UpdateEmployee
 
public class CreateEmployee{
@precondition
public void Create_Organization()
{
//Organization Creation code goes here
//Create_Organization method of CreateOrganization testcase and 
//Create_Organization method of CreateEmployee testcase are different and has no link/relation in between
}
@precondition
public void Create_Employee()
{
//Employee Creation code goes here

}
@Test 
public void Update_Organization()
{
//Creation of org code goes here
}
@Cleanup
//Cleanup code goes here ...here we delete all the test data created in the test. 
//Application goes back to original condition.
public void Delete_Organization()
{
}
public void Delete_Employee()
{
}
}


Advantages

  • Fully Structured and independent to each other so no problem to pickup any testcase and execute.
  • No polluted or corrupted test data propagation between tests
  • Uniquely identify the issues with testdata
  • Easy reporting and rerun report generation.

Disadvantages
  • Lot of refactoring required if we have a large test inventory prepared in other model
  • Need to prepare test data for atomic test cases which is a hectic job.
  • Execution time increases by multiple times.
So we need to take a conscious call if we will follow the hermetic design or batch mode test design . Mainly if we test a flow based scenario it is always better to go for batch mode test design.Other wise we must follow atomic test pattern or hermetic test pattern.
With hermetic test pattern we will be able to randomize our test execution.I always try to make testcases independent. If not possible or if that does not make sense, I go for batch mode or bunch mode and tag them differently.Mostly Smoke testcases[a set of testcases running day and night to make sure build is stable and correct],I prefer them independent and execute them in random order.

image Credit:pro-it-service.com
Shall We Execute Our Automation Testcases in Random Order?? Shall We Execute Our Automation Testcases in Random Order?? Reviewed by Animesh on September 28, 2015 Rating: 5

How To Solve Popup Issues in Selenium

September 19, 2015
If there is a scenario where we have to download a file ,usually we get a pop up asking us to click on open save or exit, this post talks about the approach how to solve this issue using selenium.
Before we go deep let us understand how many types of pop up available in Browser world.
There are mainly 3 types of pop up available.

  • JavaScript Popup
  • Browser Popup
  • Native OS popup

Now Selenium can really handle Javascript and Browser popup. Selenium has full control over them. But for Native Window's or OS's popup,selenium could do .
Selenium provides an API to handle JavaScript PopUps out of the box.
Alert alert = driver.switchTo().alert();
Now there are four different methods available to handle the popup.

  • accept()
  • dismiss()
  • getText()
  • sendKeys()
Using these Javascript and browser popups can be handled properly.
But for Native popups we need to take different approaches.

One approach given here to exclude these testcases. It may be possible to convince the customer about the downside of this problem.But if atall we need to perform this operation we may take the following approaches.

The approaches available are:
  • Disable Popup
  • Using Profile
  • Preference
  • Using Sikuli
  • Using AutoIT
  • Using Robot


Disable Popup

In this approach we disable the popup from browser setting and command it what's to be done.It we need to download.We provide that here and give path where we need to download. During run after this step,We copy the downloaded file to our required path. During run popup will not open rather file will be downloaded to the path given. More detailed steps can be found here
Using Profile

Some use profiler concept to handle download popup. The code will look like below:
FirefoxProfile profile = new FirefoxProfile();
        String path = "D:\\Download\\";
        profile.setPreference("browser.download.folderList", 2);
        profile.setPreference("browser.download.dir", path);
        profile.setPreference("browser.download.alertOnEXEOpen", false);
        profile.setPreference("browser.helperApps.neverAsksaveToDisk", "application/x-msexcel,application/excel,application/x-excel,application/excel,application/x-excel,application/excel,application/vnd.ms-excel,application/x-excel,application/x-msexcel");
        profile.setPreference("browser.download.manager.showWhenStarting", false);
        profile.setPreference("browser.download.manager.focusWhenStarting", false);
        profile.setPreference("browser.helperApps.alwaysAsk.force", false);
        profile.setPreference("browser.download.manager.alertOnEXEOpen", false);
        profile.setPreference("browser.download.manager.closeWhenDone", false);
        profile.setPreference("browser.download.manager.showAlertOnComplete", false);
        profile.setPreference("browser.download.manager.useWindow", false);
        profile.setPreference("browser.download.manager.showWhenStarting", false);
        profile.setPreference("services.sync.prefs.sync.browser.download.manager.showWhenStarting", false);
        profile.setPreference("pdfjs.disabled", true);

        WebDriver driver = new FirefoxDriver(profile);
It is described here.But many a times it failed.

Using Preference


The Code will be
profile.set_preference("browser.download.panel.shown", False)
profile.set_preference("browser.helperApps.neverAsk.openFile","text/csv,application/vnd.ms-excel")
profile.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/csv,application/vnd.ms-excel")
profile.set_preference("browser.download.folderList", 2);
profile.set_preference("browser.download.dir", "c:\\firefox_downloads\\")
browser = webdriver.WebDriver(firefox_profile=profile)

It is described here
Using Sikuli


public class WebdriverSikuli {

    private WebDriver driver;
    private String baseUrl;
    private Screen screen;

    @BeforeSuite
    public void setUp() throws Exception {
                         driver = new FirefoxDriver();
                         screen = new Screen();
//Give link of the URL from where the download starts
                         baseUrl = "download URL";
                         driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    }

    @Test
    public void testUntitled() throws Exception {
                         driver.get(baseUrl + "/");
//Give cordinates where it needs to go
                         driver.findElement(By.linkText("20.30.0")).click();
                         screen.click("images/SaveFileButton.png");
    }

    @AfterSuite
    public void tearDown() throws Exception {
                         driver.quit();
    }
}



Using Robot

This is applicable when the interaction is very limited. Using Robot class we can simulate KeyPress,Tabkeys,Mouse move etc.  But all events happen either on keyboad or based on screen coordinates. So can perform on a single screen resolution. Slight difference in screen resolution may fail test execution. It depends on the focus too. If Focus got shifted from one place to another before invoking this method. It is bound to fail.No String support for keyboard event.It can throw only one character at a time.So little time consuming. It can not capture the property value of the popup like title,String inside the popup. So no custom approach can be taken based on the failure message of the popup. It handles all pop up in a same way. A detailed approach can be found here

Using AutoIT
AutoIT is one of the tool that can automate the windows operation. it creates executable script which can be called from selenium.It is based on image comparison. During creation of the script we provide the popup picture and asks it to compare for the same image during runtime. If matches then it perform the set of operations we want it do. This method is highly dependent on Screen resolution,So it will work exactly same or greater resolution not lesser resolution.
More details can be found here.

image credit:bharath-marrivada.blogspot.com
How To Solve Popup Issues in Selenium How To Solve Popup Issues in Selenium Reviewed by Animesh on September 19, 2015 Rating: 5

How To Convert JUnit Report Produced by ANT to Excel

August 26, 2015
ANT-Excel Reporting is an important area where automation needs to fine-tune.
Every test should have some objectives. That is finite and achievable. So reports coming straight from automation tool should tell clearly the result of the testcase. There could be two options pass or failed. If failed if it gives the reason and if can pinpoint if there is already any bug on that, that would be awesome. Otherwise result may mislead the testing.Result should also provide screenshots for passed and failed, testdata, environment details , step details and other information to nail the issue.
Now analysis of these failures are tedious and boring job, takes several time of a test engineers.With meaningful failure message, it is possible to automate the result analysis part. the below section talks about the automation of such report coming straight from JUnit.Many a times, we need to convert JUnit report to Excel. Some need this for his own reporting purpose. Functional QA needs it for analysis and documentation. Automation test engineers need this converted data for
further script/test fix.
I tried to google the same.
I found this-Convert an XML file into an Excel spreadsheet 
with this technique. Here the technique is little complex.
I found in google many test engineers need this for their analysis.
 And most of them around 16 links in google to find out the failed
and Error testcases.

I am creating a simple project to extract all errors and failure testcases in excel.

To run this what you need:
Java 1.7
JSoup latest
Eclipse
POI
Before we really start please go through the below links for further understanding:
  1. JSoup A Nice Initiative To Fetch Information From HTML
  2. How To Read Data From HTML Via JSoup In Java
The algorithm is as follows:
  1. Take JUnit report from User using swing input
  2. Read all tables and filter out errors and failures into two different lists using JSoup
  3. Create Excel and sheet using POI
  4. Put all data into the sheet using POI and java
Implementation:
So the first step take eclipse or any java editor. Install or extract into a folder. Create a workspace for this. Now create a project. The structure of the project will look like--
Project Structure

























Name of the project-Result Analyser.
Now while coding our first objective to create
 a user interface. From this interface user will
 will provide JUnit report to the system.

input
Code for user Input:

package main.java;
import javax.swing.JOptionPane;
public class Client {
public static void main(String[] args) throws Exception { 
 
        ReadHTML readHtml=new ReadHTML(); 
        readHtml.getValues(JOptionPane.showInputDialog("Please input mark for test 1: "),"Test"); 
        CreateExcelFile cef=new CreateExcelFile(); 
        cef.getExcelFileName();

    }

} 

Now I am creating an Object ReadHTML.So let us implement ReadHTML

package main.java;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;


public class ReadHTML {
 public  void  getValues(String url,String SheetName) throws Exception
 {
  String overViewSummaryURL=url+"overview-summary.html";
  String allFailureDetailsURL=url+"alltests-fails.html";
  String allErrorDeatilsURL=url+"alltests-errors.html";
  System.out.println("Processing Overview Summary");
  URL getUrl=new URL(overViewSummaryURL);
  Document doc = Jsoup.parse(getUrl, 3000);
  Element table = doc.select("table[class=details]").first();
  Iterator<Element> iteh = table.select("th").iterator();
  //This is for fetching header values
  String test= iteh.next().text();
  String fail= iteh.next().text();
  String err= iteh.next().text();
  String knonIss=iteh.next().text();
  String pass= iteh.next().text(); 
  String skip= iteh.next().text();
  String suc_rate=iteh.next().text();
  String time=iteh.next().text();

  Iterator<Element> ite = table.select("td").iterator();

  //This is for fetching row values
  String testV=ite.next().text();
  String failV=ite.next().text();
  String errorV=ite.next().text();
  String knownIssueV=ite.next().text();
  String passV=ite.next().text();
  String skipV=ite.next().text();
  String sucv=ite.next().text().split(":")[1].split("%")[0].trim();
  String timeV=ite.next().text();

  System.out.println("Value of: "  +test+  " is " + testV );
  System.out.println("Value of: "  +fail+  " is " + failV);
  System.out.println("Value of: "  +err+  " is "  +errorV);
  System.out.println("Value of: "  +knonIss+  " is " +knownIssueV );
  System.out.println("Value of: "  +pass+  " is "  +passV);
  System.out.println("Value of: "  +skip+  " is "  +skipV );
  System.out.println("Value of: "  +suc_rate+  " is " + sucv);
  System.out.println("Value of: "  +time+  " is " +timeV );
  System.out.println("Processing All Failure Summary");
  getUrl=new URL(allFailureDetailsURL);

  Document docfailure = Jsoup.parse(getUrl, 3000);
  Elements tableFailure = docfailure.select("table[class=details]");

  int rowCount=tableFailure.select("tr[class=Failure]").size();
  

  System.out.println(rowCount+"row");

  System.out.println("Processing All Failure Summary result");

  List<List> recordToAdd = new ArrayList<List>();
  
  List<String> headerRow = new ArrayList<String>();
  
  headerRow.add("Class Name");
  headerRow.add("Script Name");
  headerRow.add("altId");
  headerRow.add("TestCase Name");
  headerRow.add("Status");
  headerRow.add("Log Information");
  headerRow.add("Class Path");
  headerRow.add("Reason for Failure");
  
  recordToAdd.add(headerRow);
  ArrayList<String>[] firstRow_rowfail_tds;
              if(Integer.parseInt(errorV)>0) {
            //List<String> firstRow_rowfail_tds = new ArrayList<String>();
            firstRow_rowfail_tds = (ArrayList<String>[]) new ArrayList[rowCount + Integer.parseInt(errorV)];
                    }
  else
                    {
            firstRow_rowfail_tds = (ArrayList<String>[]) new ArrayList[rowCount];
                    }
            int i=0;
          for (Element tablefail : docfailure.select("table[class=details]")) {
           for (Element rowfail : tablefail.select("tr[class=Failure]")) {
    Elements tds = rowfail.select("td");
                
    System.out.println("Class Name - " + tds.get(0).text());  
    System.out.println("Script Name - " + tds.get(1).text());
    System.out.println("altId - " + tds.get(2).text());
    System.out.println("TestCase Name - " + tds.get(3).text());
    System.out.println("Status- " + tds.get(4).text());
    System.out.println("URL-->"+tds.select("a").attr("href"));
    System.out.println("");  
   firstRow_rowfail_tds[i] = new ArrayList<String>();
     
     firstRow_rowfail_tds[i].add((String) tds.get(0).text());
     firstRow_rowfail_tds[i].add((String) tds.get(1).text());
     firstRow_rowfail_tds[i].add((String) tds.get(2).text());
     firstRow_rowfail_tds[i].add((String) tds.get(3).text());
     firstRow_rowfail_tds[i].add((String) tds.get(4).text());
     firstRow_rowfail_tds[i].add((String) tds.get(5).text());
     firstRow_rowfail_tds[i].add((String) getClassInformation(tds.select("a").attr("href"),(String) tds.get(0).text()));
                    recordToAdd.add(firstRow_rowfail_tds[i]);
     System.out.println(recordToAdd);
     i=i+1;
     System.out.println(i+"val of i");
     if (i==tablefail.select("tr[class=Failure]").size())
      break;
   }
  }
        System.out.print("errorV"+errorV);
  if(Integer.parseInt(errorV)>0)
  {
     getUrl=new URL(allErrorDeatilsURL);
  Document docError = Jsoup.parse(getUrl, 3000);
  Elements tableError = docError.select("table[class=details]");
  int rowCountError=tableError.select("tr[class=Error]").size();
     System.out.println(rowCountError+"row");
  System.out.println("Processing All Error Summary result");
  int j=0;
  for (Element tablefailError : docError.select("table[class=details]")) {
   for (Element rowfailError : tablefailError.select("tr[class=Error]")) {
    Elements tds = rowfailError.select("td");
                
    System.out.println("Class Name - " + tds.get(0).text());  
    System.out.println("Script Name - " + tds.get(1).text());
    System.out.println("altId - " + tds.get(2).text());
    System.out.println("TestCase Name - " + tds.get(3).text());
    System.out.println("Status- " + tds.get(4).text());
    System.out.println("");  
     firstRow_rowfail_tds[i+j] = new ArrayList<String>();
     firstRow_rowfail_tds[i+j].add((String) tds.get(0).text());
     firstRow_rowfail_tds[i+j].add((String) tds.get(1).text());
     firstRow_rowfail_tds[i+j].add((String) tds.get(2).text());
     firstRow_rowfail_tds[i+j].add((String) tds.get(3).text());
     firstRow_rowfail_tds[i+j].add((String) tds.get(4).text());
     firstRow_rowfail_tds[i+j].add((String) tds.get(5).text());

     firstRow_rowfail_tds[i].add((String) getClassInformation(tds.select("a").attr("href"),(String) tds.get(0).text()));
     recordToAdd.add(firstRow_rowfail_tds[i+j]);
     System.out.println(recordToAdd);
     j=j+1;
     System.out.println(j+"val of j");
     if (j==tableError.select("tr[class=Error]").size())
      break;
   }

        }
  }
  System.out.print("recordToAdd"+recordToAdd);
  CreateExcelFile cls = new CreateExcelFile(recordToAdd,SheetName);


 }

 private String getClassInformation(String attr, String text) {
        attr.toString();
  // TODO Auto-generated method stub
  return null;
 }

 
 
}


Now I am creating another object class:CreateExcelFile CreateExcelFile cef=new CreateExcelFile(); So let us implement CreateExcelFile class:

package main.java;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

/*
 * Here we will learn how to create Excel file and header for the same.
 */
public class CreateExcelFile {

  int rownum = 0;
  HSSFSheet firstSheet,SecondSheet ;
 Collection<File> files;
  HSSFWorkbook workbook;
 File exactFile;
 {
  workbook = new HSSFWorkbook();
  firstSheet = workbook.createSheet("FIRST SHEET");


  Row headerRow = firstSheet.createRow(rownum);
  headerRow.setHeightInPoints(40);
 }
 public CreateExcelFile(){
 }
 CreateExcelFile(List<List> l1,String FileName) throws Exception {
  FileOutputStream fos = null;
  try {
   workbook = new HSSFWorkbook();
   firstSheet = workbook.createSheet("FIRST SHEET");

   }
        catch (Exception e)
        {
   e.printStackTrace();
  }
  
  try {
                for (int j = 0; j < l1.size(); j++) {
             Row row = firstSheet.createRow(j);
    List<String> l2= l1.get(j);
    for(int k=0; k<l2.size(); k++)
    {
     Cell cell = row.createCell(k);
     cell.setCellValue(l2.get(k));
    }
    rownum++;
   }

  } catch (Exception e) {
   e.printStackTrace();
  } finally {

  }

  fos=new FileOutputStream(new File(getPath(FileName)));
        System.out.print(getPath(FileName));
  HSSFCellStyle hsfstyle=workbook.createCellStyle();
  hsfstyle.setBorderBottom((short) 1);
  hsfstyle.setFillBackgroundColor((short)245);
  workbook.write(fos);
        fos.close();
        
        
 }
    
public String getTimeStamp()

{
return new SimpleDateFormat("yyyyMMdd").format(Calendar.getInstance().getTime()); 
}
public String getPath(String FileName) throws IOException
{
 String path=new File(".").getCanonicalPath() + File.separator;
 //path=path+getTimeStamp()+"analysis"+".xls";
    path=path+"analysis_"+FileName+".xls";
 return path;
}

public String getExcelFileName()
{String path="";
    try {
         path=new File(".").getCanonicalPath() + File.separator;
    } catch (IOException e) {
        e.printStackTrace();
    }
    int totalFileCount = 0;
     int fileCount = 0;
     ArrayList<String> aList = new ArrayList<String>();
    File folder = new File(path);
    File[] listOfFilesInDirectory = folder.listFiles();
    try {
        for (int numberOfFilesInFolder = 0; numberOfFilesInFolder < listOfFilesInDirectory.length; numberOfFilesInFolder++) {

            if (listOfFilesInDirectory[numberOfFilesInFolder].isFile()) {
                totalFileCount++;
                String files = listOfFilesInDirectory[numberOfFilesInFolder]
                        .getName();
                if (files.endsWith(".xls") || files.endsWith(".XLS")
                        || files.endsWith(".xlsx")
                        || files.endsWith(".XLSX")) {
                    aList.add(files);
                    fileCount++;
                }
            }
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println("Total file count = " + totalFileCount);
    System.out.println("Required file count = " + fileCount);

    return "";
}
}

That's it. Now run your client to fetch the JUnit report. After Processing it will create the excel with all failures,Errors and known issues with the failure message in excel.

The output will be:

The output excel will look like-
With this report a automatic excel will be generated to give proper guidance  to automation test engineer to analyze more in details.
As we know advertisement plays a great role or huge role in terms of successful products. It creates the awareness among the consumer of the products. Sharing the extract from test automation result with management and other stakeholders play a significant role for advertisement of automation. It is having multi folded benefits..
1. All stakeholders become serious while developing or making changes in application. Slowly they tend to think about testing team which intern gives birth of test driven development.
2.All shareholders become aware about the effort automation test engineers putting into automating the application. This gives a solid management backing.
3. Bugs caught in automation gets visible in very early stage in very quick time. Also automation logs shows the different areas, it touched. Functional QA and dev team will have a clear idea where the application is working fine and where it is broken.
How To Convert JUnit Report Produced by ANT to Excel How To Convert JUnit Report Produced by ANT to Excel Reviewed by Animesh Chatterjee on August 26, 2015 Rating: 5

Which is better Xpath or DOM?

August 07, 2015
DOM:
The Document Object Model (DOM) is a cross-
platform and language-independent convention for
representing and interacting with objects in HTML,
XHTML and XML documents. Objects in the DOM
tree may be addressed and manipulated by using
methods on the objects.
Ex: var element=document.getElementById("intro");
XPATH:
XPath, the XML Path Language, is a query language
for selecting nodes from an XML document. In
addition, XPath may be used to compute values
 (e.g., strings, numbers, or Boolean values) from the
content of an XML document.
Ex: //input[@id=”xxx”]
 
They are complementary rather than competing. DOM provides a tree model of XML with low-level navigation capability (get first child, get next sibling, etc); XPath adds a much higher-level search and navigation capability

Note also that DOM is just one tree model for XML, and is very far from being the best: it's the first and the worst, and it's a shame that so many people still use it. In the Java world there are much better designs available such as JDOM and XOM.
But as starter I will remember DOM as the database and xpath is the SQL query.
Absolute Xpath :
1) start selection from the document node
2) Starts with //
3) e.g. “/html/body/p” matches all the paragraph elements
Google Search Box : /html/body/div[1]/div[2]/div[1]/div[1]/div[3]/div/div/div/form/fieldset[2]/div/div/div
Relative Xpath  :
1) start selection matching anywhere in the document
2) Starts with /
3) e.g. “//p” matches all the paragraph elements starts with p
Google Search Box : //*[@id='gbqfqwb']

image credit:developer.chrome.com
Which is better Xpath or DOM? Which is better Xpath or DOM? Reviewed by Animesh Chatterjee on August 07, 2015 Rating: 5

Commonly Used Clipboard Objects in Testing

August 07, 2015
ClipBoard class is used for a Transferable object and can be used for Cut,Copy,Paste operation.
This is used to get or transfer/send information via Clipboard Mostly Java has two types of clipboards. Local and system.
Local clipboards are only available inside the virtual machine that  your applet or application is running. However, unlike some
operating systems that limit you to only one clipboard, Java allows  you to have as many local clipboards as you desire. Accessing a particular local clipboard is as easy as referring to it by name.System clipboards are directly linked with the peer operating system, allowing your application to transfer information among
any applications running under that operating system. One  disadvantage of using the system clipboard is that you can only 
transfer text data. Other types of objects are not supported  by the system clipboard. With any luck, this issue will be addressed in  the next release of the JDK.

NameTypeDescription
ClipboardClassDeals with everything that is a transferable
ClipboardOwnerInterfaceEvery class that deals with the clipboard must implement this interface. This interface is used to notify when the data originally placed in the clipboard has been overwritten
DataflavorClassRepresents all the data types that transferable support
StringSelectionClassOne type of transferable that is supplied with Java
TransferableInterfaceWrapper to objects passed to the clipboard
ExceptionClassException thrown by transferable for an unsupported data flavor


The clipboard Class:
MethodDescription
String getName ()Get the name of the clipboard
void setContents (Transferable, ClipboardOwner)Set the content of the clipboard along with owner object
Transferable getContent (Object)Get the content of the clipboard in the form of a Transferable object. The object passed as a parameter is the owner

To access the system clipboard:
Clipboard clip=getToolkit().getSystemClipboard();


The ClipBoard Owner Interface:
 Its sole function is to inform the owner of the clipboard when his or her data is being overwritten by someone else. It can also signal an application when to release a resource associated with the data. In a real application, the lostOwnership method could be used to set a flag that informs your application about the availability of the data in the clipboard. Microsoft Word, while not written in Java, is a good example of this mechanism at work in an application. Whenever you put something in the clipboard within Word and then quit, a dialog box appears informing you that data is in the clipboard. You will then be asked if you want to leave the data in the clipboard.
 The DataFlavor class


The DataFlavor class is used to represent the type of an object. You're not limited to one data flavor (or type) per object. And, like us, your objects can have multiple personalities! For example, an image class can be represented as a Java class or as an array of bits (GIF, JPEG, and so on). In reality, a DataFlavor class is a wrapper to a MIME type. The MIME standard is extensive, hence there are virtually no limits to the data that can be transferred to the clipboard. 

boolean equals (DataFlavor)Test if the DataFlavor supplied is equal to the DataFlavor represented by this class
String getHumanPresentableName ()Return the human representable name for the format that this DataFlavor represents
void setHumanPresentableName (String)Set the human representation name for this DataFlavor
String getMimeType ()Get the MIME type string represented by this DataFlavor
Class getRepresentationClass ()Return the Class that represents this class

The Transferable interface
The Transferable interface must be implemented by all classes that you want to send to the clipboard, hence the Clipboard class will only understand classes that have been wrapped by the Transferable interface. The Transferable interface is comprised of three methods:
Transferable interface
MethodsDescription
DataFlavor getTransferDataFlavor ()Return an array of DataFlavor that represents the object
boolean isDataFlavorSupported (DataFlavor)Test if the DataFlavor supplied is supported
Object getTransferData (DataFlavor)Return the object represented by the supplied DataFlavor
Commonly Used Clipboard Objects in Testing Commonly Used Clipboard Objects in Testing Reviewed by Animesh Chatterjee on August 07, 2015 Rating: 5

How To Create Test Data for Advanced Test Structure or Test Framework

August 07, 2015
In my last couple of posts, Structure of Automation Test Cases and
Best Test Structure::Hermetic Test Pattern , I have shown each testcase
should be independent to each other. But to make them real
independent it requires testdata manipulation. Testdata also need to
be independent ad unique in nature.

Why it is required?
It is required to stop data pollution.Stop using polluted data usage
inflow and outflow. 
I am writing few common methods to make testdata independent:

Ways:
  1. Use testcase id or name at the end of the testdata like Cutomer_Name=”Rabin”+”Test123”;
  2. Use time stamp to make testdata unique like-Customer_Name=”Rabin”+”3103201515082015”;
  3. Use random number generator to create unique testdata.like-“Robin”+rand.nextInt(900) + 100;
I like the Random number generation method and if it is not possible to use, I generally use the testcase id.
More note on Random number generation:
RandomStringUtils.random(10, false,true);

you need to import - org.apache.commons.lang3.RandomStringUtils package
this is very useful when generating 10 digit random number.
AtomicInteger counter = new AtomicInteger(1);
counter.getAndIncrement();

This is also very useful to get unique number.


image credit:http://www.sqledt.com/
How To Create Test Data for Advanced Test Structure or Test Framework How To Create Test Data for Advanced Test Structure or Test Framework Reviewed by Animesh Chatterjee on August 07, 2015 Rating: 5

Best Test Structure::Hermetic Test Pattern

August 07, 2015
In my last post-Structure of Automation Test Cases, I have shown how we can improve the test structure and make a better one.Too many tests will make feedback loop delayed and too less tests may not have enough coverage.Sometimes too many tests are added to a single E2E(End to End) script.This kind of test design will make it spaghetti. The goal is to design a significant approach that will lower down the feedback loop.
Now lets looks at the question below:

  • What is the biggest benefit or goal ? 
  • What is the cost ? 
  • How is the team? 
  • What training team needs? 
  • What is holding automation back? 
We have to prioritise the issues and resolve one by one. Now in this post I am trying to venture the pattern on which the structure is made. The test structure is made on Hermetic Test Pattern. As per the Hermetic test pattern each test should be completely Independent and should not depend on other test. So,It should be atomic in nature and self sufficient.As per the maintenance concern,each test case should be maintained concern,each testcase should be maintained separately and if any dependency outside of the test found(may be a 3rd party library,3rd party service) test engineer should cut the linkage with the service.
The best way to start is to look into smaller objectives but add test slowly to make it mature.
Advantages: Each testcases are atomic in nature so no dependency on anything. Test takes clean start as precondition creates all test data No polluted data inflow our outflow. We can execute the test in different order on need based. We can create more molecularity which increase code re usability. As each testcase is atomic,parallel execution is still possible.The deep advantages are:

  1. Increase confidence in software quality.
  2. Earlier time to produce the software to the market means more revenue.
  3. Reduce the cost in testing.
  4. Consistent repeatable testing
  5. Run tests unattended.
  6. Find more regression bugs
  7. Run tests more often
  8. Better quality software
  9. Coverage is high
  10. Find more bugs
  11. Test on different systems.


Disadvantages: Duplication of code increases if not created modular type. Design testdata for each testcase Execution time increases. High resource utilisation.
Best Test Structure::Hermetic Test Pattern Best Test Structure::Hermetic Test Pattern Reviewed by Animesh Chatterjee on August 07, 2015 Rating: 5

What Should Be The Structure of Automation Test Cases

August 04, 2015
A perfectly structured automation testcase should consist of four parts. They are:

  • Setup or precondition
  • main test
  • Cleanup or post condition
  • Optional code.


Precondition: All test data ot steps needs to be there in application or needs to be performed so that current test run/execute smoothly.

Main test: In this area the main objective of test case is being executed.

Cleanup: Here we delete all the testdata that is being created in the main test section.In other word we try to restore the out of box condition of the application. Why this is required?? Any accidental data pollution can be rectified.

Optional Area: All other user defined functions go here.
Class testcase1
{
precondition()
{
}
main()
{
functionx()
}
cleanup()
{
}
functionx()
{
}
}

Why we should do like this?

  • Well, while developing or refactoring we must understand our test goal.Each testcase should address only one requirement. Multiple requirement coverage in a single automation test may lead to confusion. It will hamper the traceability matrix as well.
  • By implementing the 3/4 folds we can reduce junk code creation. More encapsulation with less junk.
  • By implementing such structure we are making testcase independent. There is no dependency such that testcaseX needs to be executed in order run current testcase.So pulling of any testcase and re execution is possible.  
  • Also, we must check if we are generating redundant code /duplicate code.The more we will reduce the duplicate code more our test will become mature.A premature optimization is the main problem area of the organization.
  • Too big component or function would reduce the flexibility of reuse. So always create smaller components or functions and assemble them in last.
  • Too small components looses it significance . Mostly we overlook them. Those created but non utilized component or functions will become zombie. It is always better to use a higher level components out of lower level components.
  • The naming convention has to be as per business requirements. then it is easy to write,find and reuse. Freeform of coding loose these advantages .
  • Each low level components has to have a definite purpose.
  • Long term survival depends on the standard approach that aids the architecture.
  • Each small function or component should have a verification point.
  • Use of wait syntax is mandatory but can be updated with do until loop.
  • When something is getting changed in the application, we need to upgrade the low level components/functions. Maintenance become easy.


What Should Be The Structure of Automation Test Cases What Should Be The Structure of Automation Test Cases Reviewed by Animesh Chatterjee on August 04, 2015 Rating: 5

How to Resolve Issue With Size() Function in Selenium for ChromeDriver

July 31, 2015

Issue Details:
In selenium execution out of ten runs six run it gives
correct result in Firefox and Internet Explorer.
But the same failed in Chrome. Always gives wrong
count when element.Size() function is triggered.
System.out.println(driver.findElements())
(By.xpath("//*[@class='test-box']")).size());



How to Solve:



1. First let us check if chrome is rendering the xpath correctly. Check the xpath.


2. Secondly,let us check if application is taking longer time to load in chrome. Use some wait time.


How to Resolve Issue With Size() Function in Selenium for ChromeDriver How to Resolve Issue With Size() Function in Selenium for ChromeDriver Reviewed by Animesh Chatterjee on July 31, 2015 Rating: 5
Powered by Blogger.