Tuesday, June 30, 2015

SELENIUM : RERUN FAILED TEST SCRIPTS USING TESTNG


There will be situations where we will re run failed automation test scripts and get the positive results upon rerun.


What if we have some utility which will rerun each failed test script..?


Yes.., We have it..we can automate rerunning test scripts scenario using IRetryAnalyzer and IRetryAnalyzer  interfaces of TestNG.


Create a Java class say RetryTest which implements IRetryAnalyzer  interface of TestNG.


Here, retryDemo() is my test method which will reexecuted on failure.
We are overriding retry() method of IRetryAnalyzer interface.
We are overriding transform() method of IAnnotationTransformer interface.


import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.IAnnotationTransformer;
import org.testng.IRetryAnalyzer;
import org.testng.ITestResult;
import org.testng.annotations.ITestAnnotation;
import org.testng.annotations.Test;

 public class RetryTest implements IRetryAnalyzer,IAnnotationTransformer {

     private int retryCount = 0;
    private int maxRetryCount = 1; //Mention how many times we want to rerun the failed test case.
   
    @Override
    public boolean retry(ITestResult result) {
     if (retryCount < maxRetryCount) {
      System.out.println("Retrying test " + result.getName()
        + " with status " + getResultStatusName(result.getStatus())
        + " for the " + (retryCount + 1) + " time(s).");
      retryCount++;
      return true;
     }
     return false;
    }
   

     @Override
    public void transform(ITestAnnotation testannotation, Class testClass,
      Constructor testConstructor, Method testMethod)    {
     IRetryAnalyzer retry = testannotation.getRetryAnalyzer();

      if (retry == null)    {
      testannotation.setRetryAnalyzer(AutomationFrameWork.class);
     }

     }
   
   
    @Test(retryAnalyzer = RetryTest.class)
    public void retryDemo() throws Exception {
     WebDriver driver = new FirefoxDriver();
     driver.get("https://www.google.co.in");
     WebElement searchBtn = driver.findElement(By.xpath("//input[@name='btnK']"));//get webelement of search button on Google Home Page.
     String actual = searchBtn.getAttribute("value");//Value: Google Search
     String expected = "Yahoo";
     Assert.assertEquals(actual, expected);
   
    }
   
    public String getResultStatusName(int status) {
     String resultName = null;
     if (status == 1)
      resultName = "SUCCESS";
     if (status == 2)
      resultName = "FAILURE";
     if (status == 3)
      resultName = "SKIP";
     return resultName;
    }

   

 }


Thats all folks…!


You have to just modify the test method: retryDemo() based upon need and enjoy.


Happy Coding !



MONKEYTALK: SCRIPT TO PROVIDE EXPLICIT WAIT IN MONKEYTALK IDE [MOBILE AUTOMATION]


There is no component or action, available in MonkeyTalk IDE for explicit wait as a step.

We can write parametrized script for the same by leveraging functionality of WaitFor action and %shouldfail modifier.




Same In MonkeyTalk language:

Vars * Define sec
View explicitlyintroducingdelay WaitFor ${sec} %shouldfail=true %timeout=120000

In this script, we are waiting for view with id <explicitlyintroducingdelay> to appear till provided number of seconds <sec>. But there is no view with id <explicitlyintroducingdelay> going to appear so script will continue after waiting for provided seconds as %shouldfail modifier is true.

Now we can call this script whenever explicit wait is required as:

Wait * ForSec 60

Above line will introduce wait for 60 seconds.


CODED UI: ADD ALL CONTROLS ON A PAGE TO THE UI MAP

One of the most frequent asks in Coded UI Test Forums is the ability to add all controls on a page to the UI Map. This can be done with the following code snippet. Here I am adding all controls on the bing start page to the specified ui test file.

[TestMethod]
public void CodedUITestMethod1()
        {
string uiTestFileName = @"D:\dev11\ConsoleApplication1\TestProject1\UIMap.uitest";
UITest uiTest = UITest.Create(uiTestFileName);
Microsoft.VisualStudio.TestTools.UITest.Common.UIMap.UIMap newMap = new Microsoft.VisualStudio.TestTools.UITest.Common.UIMap.UIMap();
newMap.Id = "UIMap";
uiTest.Maps.Add(newMap);

GetAllChildren(BrowserWindow.Launch(new Uri("http://bing.com")), uiTest.Maps[0];);
             uiTest.Save(uiTestFileName);
        }
private void GetAllChildren(UITestControl uiTestControl, Microsoft.VisualStudio.TestTools.UITest.Common.UIMap.UIMap map)
        {
foreach (UITestControl child in uiTestControl.GetChildren())
            {
                map.AddUIObject((IUITechnologyElement)child.GetProperty(UITestControl.PropertyNames.UITechnologyElement));
                GetAllChildren(child, map);
            }
        }

Let us look at what the code snippet does.

UITest uiTest = UITest.Create(uiTestFileName);

This line of code creates a UITest object from a file. Here I am assuming that we have an empty UITest file. You can add an empty UI Test file to your Test Project by right clicking on the Test Project and choosing Add –> New Item –> Coded UI Test Map.
Microsoft.VisualStudio.TestTools.UITest.Common.UIMap.UIMap newMap = new Microsoft.VisualStudio.TestTools.UITest.Common.UIMap.UIMap();
newMap.Id = "UIMap";
uiTest.Maps.Add(newMap);
These 3 lines create a new UIMap object and adds it to UITest object
GetAllChildren(BrowserWindow.Launch(new Uri("http://bing.com")), uiTest.Maps[0];);
The next line launches the browser, navigates to bing.com and passes a reference to the browser & the UIMap object to GetAllChildren method.  GetAllChildren recursively gets the children of the browser object and adds them to the UIMap.

In the interests of brevity and ease of description, I have not handled error & exception conditions.  You can now customize the code based on your need. Instead ofGetChildren, you can use FindMatchingControls to add all controls of a specific type.




Credits: Mathew Aniyan's Blog

Monday, June 29, 2015

DIFFERENCE BETWEEN / AND // - SELENIUM XPATH

/

When / is used at the beginning of a path:

/div
it will define an absolute path to node "a" relative to the root. In this case, it will only find "a" nodes at the root of the XML tree.


//

When // is used at the beginning of a path:

//div

It will define a path to node "div" anywhere within the XML document. In this case, it will find "div" nodes located at any depth within the XML tree.


These XPath expressions can also be used in the middle of an XPath value to define ancestor-descendant relationships. When / is used in the middle of a path:


/div/a

it will define a path to node "a" that is a direct descendant (ie. a child) of node "div".


When // used in the middle of a path:

/div//a

It will define a path to node "a" that is any descendant (child node)  of node "div".


When we don't know the immediate parent of a child then we can use "." dot

will still find any node, "div", located anywhere within the XML tree. But, the XPath:

.//div

will find any node, "div", that is a descendant of the node . " In other words, preceding the "//" expression with a "." tells the XML search engine to execute the search relative to the current node reference.





DIFFERENCE BETWEEN SIMULATION AND EMULATION - Awesome answer

You must have seen multiple answers for this question. But below one is awesome.

You want to duplicate the behavior of an old calculator, there are two options.

  1. You write new program that draws the calculator's display and keys, and when the user clicks on the keys, your programs does what the old calculator did. This is a Simulator
  2. You get a dump of the calculator's firmware, then write a program that loads the firmware and interprets it the same way the microprocessor in the calculator did. This is an Emulator
The Simulator tries to duplicate the behavior of the device.
The Emulator tries to duplicate the inner workings of the device.


Simulator is similar to something.
Emulator is exactly like something.

KEYBOARD OPERATIONS IN SELENIUM WEBDRIVER


The Keys class library allows us to reference the non alphabet/ text keys on the keyboard. This applies to keyboard keys like the ARROW keys, ALT, CTRL etc. Of course for text entries like "John", we can simply write: 



WebElementVariable.sendKeys("John");



The following codes will call the browser, load the google website and then simulate making an entry of "1999" into the search text box.



import org.openqa.selenium.By;

import org.openqa.selenium.Keys; 
import org.openqa.selenium.WebDriver; 
import org.openqa.selenium.WebElement; 
import org.openqa.selenium.firefox.FirefoxDriver; 

public class KeyboardOperations { 

         public static void main(String[] args) { 
                WebDriver driver = new FirefoxDriver(); 
                driver.navigate().to("http://www.google.co.uk"); // Actual loading of website 
               System.out.println("Make entries into Google Search using keyboard actions"); 
               WebElement searchInput = driver.findElement(By.className("gbqfif")); 
               String allKeys = ""+ Keys.NUMPAD1 + Keys.NUMPAD9 + Keys.NUMPAD9 + Keys.NUMPAD9; // 1 + 9 + 9 + 9 
               allKeys = allKeys + Keys.ENTER; // now add the ENTER key. We could also have done it above 
               searchInput.sendKeys(allKeys); // send the key presses into the text box 
        } 






Credits: http://www.logicandtricks.com/

CAPTURE A SECTION OF SCREEN USING SELENIUM WEBDRIVER


Capturing a section of the screen involves:
1) Performing a screen capture as usual and saving the created image to disk.
2) Getting the saved image and cutting/ cropping out a section of it as required into another image file.


import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.imageio.ImageIO;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class CaptureScreenSection {

public static void main(String[] args) throws IOException {

//Initialise firefox browser
WebDriver driver = new FirefoxDriver();

/* Next line makes the browser wait for 7 seconds before declaring it cant find an element. 
Good for slow loading websites*/
driver.manage().timeouts().implicitlyWait(7,TimeUnit.SECONDS);
driver.get("http://www.sojicity.com/"); 

// Step 01: Take Screen shot and create the file
System.out.println("Taking Screen Shot");
File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("c:\\logicandtricks\\screenshot.jpg"));

// Step 02: Cut/ Crop out a section of the saved photo above and save the cropped photo
Image orig = ImageIO.read(new File("c:\\logicandtricks\\screenshot.jpg"));
int x = 10, y = 20, w = 500, h = 510;  // define the sections to cut out
BufferedImage bi = new BufferedImage(w, h, BufferedImage.OPAQUE);
bi.getGraphics().drawImage(orig, 0, 0, w, h, x, y, x + w, y + h, null);
ImageIO.write(bi, "jpg", new File("c:\\logicandtricks\\screenshot_cropped.jpg"));

}





Credits: http://www.logicandtricks.com/

10 BASIC RULES FOR BEGINNERS IN AUTOMATION TESTING

Testing is a hard task and automating it is a dream of every tester or developer. However, automation requires deep understanding of the process and constant practice along with following basic guidelines. We will describe these guidelines in this article to show you automation is done easily when done right.
RULE 1: READ THE BASICS AND LEARN THEM
Even skilled developers need to revise their knowledge from time to time, learning is a must. Automation is nothing but a mere evaluation of steps the program must perform, writing a detailed instruction.
RULE 2: BE PREPARED TO MEET THE AUTOMATION PROJECT
Practice is the only way to get valid knowledge. Grab any open source testing tool available, install it and learn using it in your free time. The sandbox may be anything, even your MS Office or Calculator tool. Just get the tool and get started, gain understanding and experience to be ready to facing the real project when need be.
Rule 3: BASIC CONCEPTS ARE THE SAME, JUST EXPLORE THEM
Apart from different peculiarities all coding languages basically operate the same concepts like variables, parameters, functions, different data types, loop or conditional statements, arrays, etc. After having these understood and remembered, you will be able to apply this knowledge to any coding language. Spare some time, a couple of weeks maybe on understanding the brick stones the code consists of.
RULE 4: DO NOT STOP AFTER THE FIRST PROGRAM FAIL
Russians have a wonderful proverb: the first pancake is a mess. It means first try on anything will most likely fail, but all the next ones will be better, as you will gain experience in the process. No matter how good you are on theory, first practice likely will be disappointing. So just go on.
RULE 5: LOOK ON CODE AS A PROCEDURE, NOT A MAGIC
Whenever beginner looks at the code, it seems nearly unbelievably complex. However, after doing some coding you will be able to recognize patterns and procedures at once, making reading the code much easier. You will see it is merely an instruction for the program, written as clear as it can be to avoid any mischief.
RULE 6: EXPLORE THE TOOL
The best way to get used to a tool is exploring its features one by one. Start with File section and click every menu, sub-menu and drop-down item all the way to Help section. Most of the items will have self-explanatory names and you will see what the others do.
RULE 7: SEARCH FOR HELP IN HELP SECTION
Whenever you are stuck feel free to read Help section of the tool. It is a wonderful source full of explanations and instructions upon every aspect of the tool’s usage. Explore it thoroughly to master the tool perfectly.
RULE 8: PRACTICE A LOT
Keep in mind testing as a validation process. It allows you to conclude if the code is functional or not. Your testing automation should be able to do the same thing, so make sure it does not give our the raw results, but the clear answer: yes or no, test passed or failed.
RULE 9: IMPROVE YOUR WORK
All things done well can be done even better. Revising and striving to improve your projects is a way to improving your skills and driving you on to new heights.
RULE 10: AUTOMATION IS NOT ALWAYS NEEDED
Despite being so useful, automation is nothing more than a tool for a tester. Really skilled testers do not need it as can read the code easily and resolve the bugs on sight. Decide the way of actions on every particular case and use manual testing or automation if needed.
CONCLUSION:
Those rules are not obligatory, yet they are simple and obvious. Following them will help you improving your skills and becoming a better tester.
If you wish to comment something, feel free to do so, as your feedback is always welcome.