Saturday, August 1, 2015

EASY TO SCROLL LISTVIEW (TABLE) TILL LAST ROW USING MONKEYTALK

Suppose there is a only ListView(Table) in the screen and you want to scroll till its last item using MonkeyTalk.

//Define a variable
Vars * Define row

//Store size of list in variable row using Get.
Table * Get row size

//Now stored variable can be used for scrolling
Table * ScrollToRow ${row}


Happy Automation !! 

EASY TO USE MONKEYTALK TEST SCRIPTS IN MULTIPLE SUB-FOLDERS

Suppose you have a project that have multiple Features. And you want to maintain test scripts for different features in different folders. This is a good practice but only problem is how to reuse script available in another folder.

You can achieve this by using TestLibrary. 

For example, you want to use Logout folder scripts in Login folder then you just need to select all required script from Logout folder and right click then select New -> TestLibrary. 
Then select the source folder [Login] where you want to create library by giving some logical name like TestLibrary_Logout.mtl

Now you can call logout.mt script available in Logout folder in login.mt (i.e. available in Login folder) as

Script louout.mt Run


Refer This for more details.

Happy Automation !!


Tuesday, July 7, 2015

EASY TO GET SAFARI WEBDRIVER RUNNING ON MAC OSX


Since this topic has not been well documented on the net and I struggled myself to get Selenium tests running on Safari browser, here are the complete set of steps to get Selenium tests up and running on Safari browsers. :-


Creating “Safari Extension” Developer Certificate

  1. Create an Apple developer account.
  • Go to https://developer.apple.com/
  • Click on “Member Center” on top panel.
  • Select “Create Apple ID”.
  • Go through the sign up forms and provide valid fields for a succesful sign up
2.  Login to created Apple account.
3.  Sign up for “Safari Extensions” developer
  • Click on “Certificates, Identifiers & Profiles”
  • In the “Safari Extensions’ section, click on “Join Now”
  • Go through the following steps and provide valid fields to successfully sign up for the “Safari Extensions” program
4.  Create “Developer Certificate”
  • Now inside “Certificates, Identifiers & Profiles” > “Click on Create/Add Safari Certificate”
  • You will see the following page – “About Creating a Certificate Signing Request (CSR)” 

  • Click on “Continue”


You will see the following page :-


  • Upload the CSR file and Click on ‘Generate’ to generate the certificate
  • Now download the certificate once it is generated.
5. Download the certificate and install in the machine
  • Download the certificate in the download tab.
  • The certificate is downloaded as “safari_extension.cer”.
  • Double-click on the file to install the certificate in the Mac client/OSX.
6.  We have installed the safari extensions certificate for developers. Now we need to install the Safari Webdriver extension for the Safari Browser.

 Installing the Safari Webdriver extension in the Safari Browser

  1. Download latest Selenium Safari extension.
2.  Install the Safari Extension
  • Double-click on the “SafariDriver.safariextz” file.
  • You will get a prompt asking “Are you sure you want to install the extension “WebDriver”?“.
  • Click on “Install”
3.  Provide the default setting for the Selenium Webdriver Extension.
  • Click on “Safari” > “Preferences” > “Extensions” > You will find Selenium extension
  • Select “Enable Webdriver”
Now all the settings are done and now we should be able to launch our Selenium scripts using Safari Webdriver.

Launching Safari Webdriver

Webdriver driver = new SafariDriver();                
driver.get( http://www.google.co.in” );
builder = new Actions(driver);
This should launch your safari browser with the Safari Webdriver Extension. :)
Hope this article comes of use to you all !!

Happy Coding !!



Credits: itisatechiesworld

Saturday, July 4, 2015

ANDROID TESTING EBOOK : EASY TO AUTOMATE ANDROID APP - "ANDROID APPLICATION TESTING GUIDE"

I found this book very helpful for Android Automation Testing concepts. It covers some very good and advanced topics. This book is must read if you are involved in Android Automation, Unit Testing or White box Testing for Android application.

Please note that it may require at least intermediate level of understanding for Android Automation.




Android Application Testing Guide




Enjoy !!

And yes don't forget to buy this book if you like it. :)




Thursday, July 2, 2015

SELENIUM : EASY TO VERIFY PDF FILE TEXT USING JAVA WEBDRIVER

In this post we will explain the procedure to verify PDF file content using java webdriver. As  some time we need to verify content of web application pdf file, opened in browser.
Use below code in your test scripts to get pdf file content.

 //get current urlpdf file url
 URL url = new URL(driver.getCurrentUrl());
                 
 //create buffer reader object
 BufferedInputStream fileToParse = new BufferedInputStream(url.openStream());
 PDFParser pdfParser = new PDFParser(fileToParse);
 pdfParser.parse();

 //save pdf text into strong variable
 String pdftxt = new PDFTextStripper().getText(pdfParser.getPDDocument());
                 
 //close PDFParser object
 pdfParser.getPDDocument().close();

After applying above code, you can store all pdf file content into “pdftxt” string variable. Now you can verify string by giving  in put.  As if you want to verify “Selenium Or Webdiver” text. Use below code.
                 
Assert.assertTrue(pdftxt.contains(“Selenium Or Webdiver”))

Hope this post will help  to verify web application PDF content.


Credits: roadtoautomation blog

Wednesday, July 1, 2015

SELENIUM : WAITING FOR CONDITIONS TO BE AVAILABLE


While testing a very slow loading website, the dreaded "NoSuchElementException" exception can occur even though the element does exist on the page. The problem can be that the code is running faster than the site loads. The "ExpectedCondition" class ensures that the program waits for a designated period of time before throwing the "NoSuchElementException" error message.


In the code below, we navigate to craigslist, take 5 seconds to wait for the required element to appear and be ready for clicking. Then click the element.

WebDriver driver = new FirefoxDriver();

// a slow loading website is good for this text. craigslist is not slow though :)

driver.get("http://london.craigslist.co.uk/");  

// define timeout for waiting period

WebDriverWait wait = new WebDriverWait(driver, 5);    

// ensures the element is available for click. Check for the defined 5 seconds before timeout

WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id='jjj']/h4/a")));   

element.click();

SELENIUM : READ BROWSER CONSOLE LOG


Initialize driver with logging preferences.




DesiredCapabilities caps = DesiredCapabilities.chrome();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.BROWSER, Level.ALL);
caps.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);
driver = new ChromeDriver(caps);
Now analyze log using below code:
LogEntries logEntries = driver.manage().logs().get(LogType.BROWSER);

for (LogEntry entry : logEntries) {
System.out.println(new Date(entry.getTimestamp()) + " " + entry.getLevel() + " " + entry.getMessage());
//do something useful with the data
}

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.