Wednesday, April 16, 2014

Sample coding logics using using Java

Problem

Write a Java program that prints the numbers from 1 to 50. But for multiples of three print "Property" instead of the number and for the multiples of five prints "Guru". For numbers which are multiples of both three and five print "PropertyGuru"

Code Snippet

package com;

public class PrintString{
public static void main(String[] args){


for(int i=1;i <=50;i++){
if (i%3==0)
if (i%5==0)
System.out.println("PropertyGuru");

if (i%3==0)
System.out.println("Property");
else if (i%5==0)
System.out.println("Guru");
else 
System.out.println(i);
}
}



}


Challenge!

Do you have better and faster way to solve the problem?

Automating real time test cases using Selenium Webdriver - 2

Test Scenario: To verify if the search results are within the specified price range.

Test Steps:

 Navigate to http://m.propertyguru.com.my/ 
 Select Min Price to 8000000 
 Select Max Price to 10000000
 Click on Search button
 Verify if the results are within the specified price range.

Note: Results Highlighted in yellow tagged with a star image should not be included on the verification. They are usually found on the first 3 rows and categorized as featured ads. Those are not part of the search results that you need to verify/assert.

Test Case Code Snippet:


package com;

import java.util.concurrent.TimeUnit;


import org.junit.Before;

import org.junit.After;
import org.junit.Test;

/*import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.chrome.ChromeOptions;*/

import org.openqa.selenium.firefox.FirefoxDriver;

import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;

public class VerifyRangeValues{

private WebDriver driver;
private String baseUrl;
// private int numToVerify;

public static String stripNonDigits(
            final CharSequence input /* inspired by seh's comment */){
    final StringBuilder sb = new StringBuilder(
            input.length() /* also inspired by seh's comment */);
    for(int i = 0; i < input.length(); i++){
        final char c = input.charAt(i);
         if(c > 47 && c < 58){ // Checking the ASCII between 48 to 57 for 0 to 9
         sb.append(c);
        }
    }
    return sb.toString();
}

public void compareNumWithRange(String strNum){
final String result = stripNonDigits(strNum);
final int a = (Integer.valueOf(result)).intValue();
System.out.println("Value extracted from string " + a);
if (a >= 8000000 && a <= 10000000){
System.out.println(a + "  is within the range 8000000 to 10000000 specified");
}
 else {
 System.out.println(a + "  is NOT withing the range 8000000 to 10000000 specified");
   
}

}


@Before
public void setUp() throws Exception{

//Uncomment the folling block and commented imports to run the code in Chrome Driver.

/*System.setProperty("webdriver.chrome.driver","E:\\D-Drive-Data\\Softwares\\Selenium Support Files\\chromedriver_win32\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized");
driver = new ChromeDriver(options);*/

driver = new FirefoxDriver();
baseUrl = "http://m.propertyguru.com.my";
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
System.out.println("SetUp executed succesfully");

}

@Test
public void testValueRange() throws Exception{
driver.get(baseUrl +"/");


Select minPriceDropdown = new Select(driver.findElement(By.id("minprice-sale")));
minPriceDropdown.selectByVisibleText("RM 800,000");

Select maxPriceDropdown = new Select(driver.findElement(By.id("maxprice-sale")));
maxPriceDropdown.selectByVisibleText("RM 1,000,000");

//driver.findElement(By.id("maxprice-sale")).sendKeys("RM 1,000,000");
//driver.findElement(By.xpath(".//*[@id='maxprice-sale']/option[1000000]"));
driver.findElement(By.id("btnSearch")).submit();

/*compareNumWithRange(
driver.findElement(By.xpath(".//*[@id='listing[0-9]{7}']/table/tbody/tr/td/div[2]/p[1]/strong/span")).getText()); */
for(int i = 4; i <11 font="" i="">
System.out.println(driver.findElement(By.cssSelector("#listings li:nth-child("+i+") strong > span")).getText());
//driver.wait(15000);

compareNumWithRange(
driver.findElement(By.cssSelector("#listings li:nth-child("+i+") strong > span")).getText());


System.out.println(i+ " testValueRange() executed succesfully");
}
}

@After
public void tearDown() throws Exception {
System.out.println("tearDown() executed succesfully");
driver.quit();
System.out.println("Webdriver Quit Successfully.");


}



}


Challenge!

Do you have a better and faster way to do this?

Thursday, February 27, 2014

Identifying and working with element that changes dynamically

There several mechanism supported by Selenium to identify the element/object on the browser and to perform some actions. There are times when identifying an element and working with it is a lot difficult. I am sharing one of the problem I faced during identifying an element that is dynamically change after each page load (each new request).

Problem

Web page loads unordered listing element with children listings that have dynamic IDs on each requests/page loads. If you identify an element and try work with selenium scripts the next time scripts run the ID would change and you'll receive dirty exception of NoSuchElementFound blah blah.

Summary outer HTML

This the HTML of the application I was trying to work with.

  •  
  • ......

    Note:
    ID and other selenium selector are not that help since every attribute is same the attributes that are different are dynamic.Therefore, you can not uniquely identify an element and work confidently with. 

    Inner HTML of the First Listing Element.

    This is the detailed HTML of the first listing element as shown above.

  • "listingItem">
  • g="0" cellpadding="0">
             PKR 850,000                       

    The value that need to be pick was PKR 850,000 (which is also changing but its position does not change)

    Solution

    Firepath CSS selector does the trick and help you evaluate your expression, by itself firepath/firebug can give the exact output as below.

    #listings li:first-child strong > span 
    #listings li:nth-child(2) strong > span 
    ...
    List goes on and on

    If the same action needs to be performed on each element this can be iterate by adding the loop as 

    for(int i = 4; i <11 div="" i="">
    System.out.println(driver.findElement(By.cssSelector("#listings li:nth-child("+i+") strong > span")).getText());
    }

    Configuring Selenium with Eclipse on Windows

    Automation is not just about recording and playback the scripts. Its actual value comes far more after you write robust reusable, repeatable and maintainable scripts. To do that you have to have the tool that support designing scripts for such purpose. Many automation tools come with scripts editor to write dynamic code that is repeatable and reusable.

    Since selenium is an opensource browser automation tool that is easily integrated in the FireFox browser to recording the application common scenarios and playing it back for verification. If you want to go further in test automation you will need a bit of liberty where you can design and develop dynamic scripts that can not be done easily with Selenium IDE.

    Required downloads


    Configuration


    • Run Eclipse (after download, unzip the folder no special installation).
    • Set you desired directory as Eclipse workspace (this where you want to save all your projects).
    • Click on File -> New -> Java Project or JPA Project.
    • Name your project, say 'Test' and click Finish
    • Right-Click on the newly created project and then click - > New -> Package
    • Name the package, say 'com' and click Finish.
    • Again right-click on the project name 'Test' and then Properties - > Java Build Path
    • Select the Library tab, if not already selected.
    • Click Add External JARs button
    • Access the path, where you downloaded it, of Selenium Java Client driver.
    • Select Zip/JARs and click Open button, all JARs would be added.
    • Click again Add External JARs button
    • Access the path, where you downloaded it, of Selenium Server Standalone.
    • Select Zip/JARs and click Open button, all JARs would be added.
    • Go to the Package 'com', right-click on it, New -> Class.
    • Name the class as 'MyTestCase'. Remember to keep it 'public' and check 'public static void main(String[] args)' and 'Inherited abstract methods'. Paste the code snippet in your Eclipse IDE.
    • Run the scripts
    Code Snippet

    package com;

    import java.util.concurrent.TimeUnit;

    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.By;
    import org.openqa.selenium.firefox.*;

    public class MyTestCase {

    /**
    * @param args
    */
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    WebDriver driver = new FirefoxDriver();
    driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
    driver.get("https://www.google.com.pk");
    driver.findElement(By.id("gbqfq")).sendKeys("Software Quality Geeks");
    driver.findElement(By.id("gbqfq")).submit();
    driver.findElement(By.linkText("Software Quality Geeks")).click();
    //driver.quit(); //uncomment this line if you want to quit browser after test run.

    }

    }


    Other things to consider

    Eclipse and Java must be of same bit architecture. For example if you are using 32 bit Eclipse then use 32 bit Java and the same is true to for 64 bit. Otherwise it would be little cumbersome to configure the cross bits eclipse and Java if you're a beginner.

    Saturday, December 28, 2013

    Things I like as tester (impersonating user) about Google - A short one.

    After using too much Google products and services I have realized that how much effort they had put up on grabbing such a vast number of people to use their products and services as a preferred choice. And why I think so I will share an example, as a tester, that is impersonating as an end user.

    Google Translate (translate.google.com)

    This is the product that I use too often while I have to see different translations for different languages (not that accurate thought :)) but it gives you enough idea about requested translation. So, I was having difficulty in grasping the word "Irony" in English to English so I picked up description of the word in English and thought of the Google Translator straightaway and before launching the http://translate.google.com the evil tester from the subconscious came into conscious mind and I used one of the way I use to join running program* with its required arguments and it was unexpected as per my evil thinking Google has tested this.

    I provided the URL as <translate.google.com "Witty language used to convey insults or scorn, esp. saying one thing but implying the opposite">and rather than getting HTTP 404 or something dirty Google did it smoothly one text box contained the requested string and other contained the requested translation. 

    I don't know whether Google tested this case explicitly but It took care of my expectation and you always go there where your expectations are honored.

    *Running and opening file simultaneously:
     
    When user want to open any file on any text editor or word processor software they usually launch the software and open file from some path, or directly go to the directory path where the file is present and double click to open it. Since I work on files that present on disparate locations so usually open the software by running it and simultaneously providing the path of the file e.g. pressing meta+R , writing notepad/winword "" and enter.

    Saturday, June 29, 2013

    Installation/Un-installation testing: Your first communication point with end-users.

    It’s been almost a year that when I last added a blog post to Software Quality Geeks. Quickly getting towards the topic that today we will be having a look at Installation Testing. This blog post or next few ones, probably soon after this one, will have the same theme that rather than writing too much about the topic we should have a look at bird eye view of any quality or testing topic. Therefore, we will be learning at installation/un-installation testing and its coverage area with help of mind-map or brainstorming diagram.
    Installation Testing is very import part of any software, because it usually requires some of sort of changes in customers or end-users machines so it must be tested carefully. Since this is the point when customer first communicates with your application, anything that goes awry at this time can cause enough damage to the business. Therefore, to avoid any potential loss to the business Installation Testing/un-installation testing should be a part of Test Plan and given enough time in testing the application as far as Installation/un-installation is concerned and for that following map can be referred and customized according the need, budget and timeframe.


    The post is not open to comments, must provide your valuable ones.


    Good luck for installation testing!

    Sunday, August 12, 2012

    Business Vs Functional Requirement


    Chaps associated with the software development whether they are software engineers, business analyst or software quality assurance professionals are often confused about Business and Functional Requirements and are not easily able to distinguish from one another.

    Let’s describe Business and Functional Requirements briefly followed by short scenario to get it right more clearly.

    Business Requirement:

    Any objective business or organization wants to achieve from software application. It could be single line statement or set of statements.

    e.g. Pakistan Government wants to take all of its operations online and each ministry will have its separate online portal to cater respective population needs.

    Presence of each business requirement in software applications is critical to its success.

    Functional Requirement:

    All the explicitly stated user requirements are considered as Functional Requirements. Also, any requirement that helps in achieving business objective but not specifically put forward by user is also considered as functional requirement.

    e.g. Authentication required to login to application. Page load time shall not increase from 5 seconds.

    Presence of each functional requirement in software applications may or may not be critical to its success.

    Let’s take a following short scenario to understand practically the difference between business and functional requirements.

    “Ministry of Education, Pakistan has decided to formulate the ratio between Pakistan’s States (Sind, Punjab, Baluchistan, KP and Kashmir) about population’s education and level of education (undergrads, grads and postgrads etc.) and devised a form for that purpose.”

    In the above statement “education ratio between states population” is the business objective (business requirement) Ministry of Education wants to achieve. For that purpose, provision (i.e. user is able to select or provide his/her state he/she lives in) of States in the application is a success criteria of the application. Now, Functional requirement in this scenario is that Combo Box (pre-filled with states Sind, Punjab etc. user may select one out of available choices) or Textbox (user may type in his/her states he/she lives in) could be provided depending upon the feasibility of application.

    Must comment if you like it.