Saturday, August 30, 2014

Insertion Sort

import java.util.ArrayList;
import java.util.List;


public class Insertion_sort {

public static void insertion(int[] arr){

int temp;
System.out.println("Before sorting");
for(int a=0; a<arr.length; a++){
System.out.print(" "+arr[a]);
}

for(int i = 1; i<arr.length; i++) {

int value_to_sort = arr[i]; // Consider the second element to sort, since first element is considered to be sorted
int j = i; // have both i and j at second place
while(j>0 && arr[j-1]>value_to_sort){//while j>0 means first place is not reached, we need to continuously move it up the ladder
//arr[j-1]>value_to_sort, if first element is greater than the swap
arr[j] = arr[j-1];
j--;//the number right not be in the right place may be it is required to move further up, so decrement j and check
}
arr[j]= value_to_sort; // finally put the number in its place
}

System.out.println();
System.out.println("After sorting");
for(int a=0; a<arr.length; a++){

System.out.print(" "+arr[a]);
}

}

public static void main(String[] args) {

int[] arr = {10, 7, 1, 2, 4, 5};
insertion(arr);
}

}

Log4j for Selenium

Apache log4j is a Java-based logging utility.
Logging helps us collect information about how the application is running and also helps us debug if any failure occurs.
With log4j it is possible to enable logging at runtime
When logging is wisely used, it can prove to be an essential tool.

There are many places you can use Log4j,
log4c - It is C based logging library
log4js - Log4js logs the events of the browser remotely on the server, with Ajax you can send logs in XML or JSON format as well
Apache Log4net - Logging for .NET framework
Similarly we have log4perl, PL-SQL-Logging-Utility and Log4db2 providing logging capability for all types of applications

Here is an example for Log4j with JAVA

1)Create a project and add an xml file log4j.xml to it and paste the following contents
Remember, log4j should be at project level, to make it available for all your scripts

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">

<appender name="fileAppender" class="org.apache.log4j.FileAppender">

<param name="Threshold" value="INFO" />

<param name="File" value="logfile.log"/>

<layout class="org.apache.log4j.PatternLayout">

<param name="ConversionPattern" value="%d %-5p [%c{1}] %m %n" />

</layout>

</appender>

<root>

<level value="INFO"/>

<appender-ref ref="fileAppender"/>

</root>

</log4j:configuration>

2) Understnading the log4j.xml

<appender name="fileAppender" class="org.apache.log4j.FileAppender">
This line will ensure your logs will get appended each you run, rather than creating a new log file for your each run

<param name="File" value="logfile.log"/>
This line will ensure it creates a file by name logfile.log at project level for all logs

<param name="ConversionPattern" value="%d %-5p [%c{1}] %m %n" />
Tells in which way you want to print your logs,

Ex
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.ConversionPattern=
      %d{yyyy-MM-dd}-%t-%x-%-5p-%-10c:%m%n

 Will create log as

 2010-03-23-main--DEBUG-log4j :

You can find more info on pattern mataching in the below link
https://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html

3)In your Framework's base script add the line

 private static Logger Log = Logger.getLogger(Log4j.class.getName());
 DOMConfigurator.configure("log4j.xml");

 Then, in each of the scripts you can use Log.info and Log.error

Ex

import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;


public class Basics_Log4j {


private static Logger Log = Logger.getLogger(Basics_Log4j.class.getName());


public static void main(String[] args) {

DOMConfigurator.configure("log4j.xml");

        Log.info("Printing Info Log from Log4j using Log.info");
        Log.debug("Printing Debug Log from Log4j using Log.debug");
        Log.error("Printing Error Log from Log4j using Log.error");
        Log.trace("Printing Trace Log from Log4j using Log.trace");
}

}

Output in logfile.log

2014-08-30 16:29:21,116 INFO  [Basics_Log4j] Printing Info Log from Log4j using Log.info
2014-08-30 16:29:21,116 ERROR [Basics_Log4j] Printing Error Log from Log4j using Log.error




Jenkins with ANT

Jenkins with ANT

With Jenkins you can perform both local builds and Remote builds, Here is an example which shows how to perform local builds

1) Start the jenkins server


In cmd prompt go to the folder where Jenkins.war and type java -jar Jenkins.war

2)Once the Jenkins server is started, open localhost:8080

3)Click on New item link to add project to Jenkins



4)Enter Project Description and select Build Free style Software Project radio button



5)In bottom of Screen, you will find, a button,Add Build Step, click on it and select Invoke Ant Option
Then click on Advanced, it will shows options as shown in picture

Enter your Ant targets and Path of Build File, Save Changes



6)Go to Dashboard and from project, select Build Now to automatically perform Build


Quick Sort

Sorting is one of the basic algorithms any SDET must know,
I'm sharing a popular and efficient Sorting algorithm, for you to add it up your sleeves

public class Quick_Sort {

public static void exchange(int[] arr, int index1, int index2){
int temp = arr[index1];
arr[index1] = arr[index2];
arr[index2] = temp;
}
public static void Quicksort(int[] arr, int low, int high) {


int i=low;
int j=high;
int pivot = arr[(i+j)/2];

//Divide the array into two parts
while(i<=j){

while(arr[i]<pivot){
i++;
}

while(arr[j]>pivot){
j--;
}

if(i<=j){
exchange(arr,i,j);
i++;
j--;

}

if(low<j){
Quicksort(arr,low, j);
}
if(i<high){
Quicksort(arr, i, high);
}
}

}

public static void printarray(int[] arr){
for(int i=0; i<arr.length; i++){

System.out.print(" "+arr[i]);
}
}

public static void main(String[] args) {

int[] arr = {10, 20, 2, 3, 24, 45, 100};
System.out.println();
System.out.println(" Before Sorting");
printarray(arr);
Quicksort(arr, 0, arr.length-1);
System.out.println();
System.out.println(" After Sorting");
printarray(arr);

}

Friday, August 29, 2014

Jenkins - Configuration/Installation

Jenkins - Configuration/Installation

Jenkins CI is the leading open-source continuous integration server.
Built with Java, it provides 975 plugins to support building and testing virtually any project.

Configuring Jenkins

1)Go to https://wiki.jenkins-ci.org and download the latest Jenkins war file
2)Go to cmd prompt and go to the folder where Jenkins.war is present
3)Type java -jar jenkins.war
Jenkins by default will start on localhost:8080, incase you need to start on a different port then use

java -jar jenkins.war --httpPort 9090
This will start Jenkins on localhost:9090

Once done it will show a message like this


Continuous Deployment

Continuous Deployment

Continuous Deployment is closely related to Continuous Integration and refers to the release into production of software that passes the automated tests
By adopting both Continuous Integration and Continuous Deployment, you not only reduce risks and catch bugs quickly, but also move rapidly to working software.

Continuous Integration - CI

Continuous Integration - CI

Continuous Integration is a development practice that requires developers to integrate code into a shared repository several times a day

Advantages of CI

1)Catch issues fast and remove them in early stages
2)Reduce integration problems allowing you to deliver software more rapidly
3)Make it easy for anyone to get the latest executable
4)Make your build self-testing
5)Automate the build
6)Maintain a single source repository

How CI Works

1)Developers check out code into their private workspace.
2)When done, the commit changes to the repository.
3)The CI server monitors the repository and checks out changes when they occur.
4)The CI server builds the system and runs unit and integration tests.
5)The CI server releases deployable artefacts for testing.
6)The CI server assigns a build label to the version of the code it just built.
7)The CI server informs the team of the successful build.
8)If the build or tests fail, the CI server alerts the team.
9)The team fix the issue at the earliest opportunity.
10)Continue to continually integrate and test throughout the project.

Things to Remember

1)Check in frequently
2)Don’t check in broken code
3)Don’t check in untested code
4)Don’t check in when the build is broken
5)Don’t go home after checking in until the system builds



JUnit - Parallel Testing

Running your tests in parallel is a powerful way to speed up your tests.
Good automated tests should be independent, isolated and reproducible, making them ideal candidates for being run concurrently
But in real world scenarios of web testing this hardly happens and when it does we must make use of JUnit parallel testing capability to speed up the testing

Example

@Test
public void Test1() {
System.out.println("In Test 1");
}

@Test
public void Test2() {
System.out.println("In Test 2");
}

@Test
public void Test3() {
System.out.println("In Test 3");
}

Runner class

@RunWith(ParallelSuite.class)
@SuiteClasses({Test1.class, Test2.class, Test3.class})
public class ABCSuite {}


Dependencies 

<dependency>
    <groupId>com.googlecode.junit-toolbox</groupId>
    <artifactId>junit-toolbox</artifactId>
    <version>2.0</version>
</dependency>

JUnit - Download and Install

Download the following jars file from http://search.maven.org/

junit.jar
hamcrest-core.jar

Maven Dependencies

JUnit

<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.11</version>
  <scope>test</scope>
</dependency>

Hamcrest

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-parent</artifactId>
<version>1.3</version>
</parent>
<artifactId>hamcrest-core</artifactId>
<packaging>jar</packaging>
<name>Hamcrest Core</name>
<description>
This is the core API of hamcrest matcher framework to be used by third-party framework providers. This includes the a foundation set of matcher implementations for common operations.
</description>
</project>

JUnit Exception Testing

In Automation, it is not only important to check if screens behave as expected with correct data, it is also important to check if tests would throw exception when invalid/inappropriate data is given, this will make the Framework more robust

Lets see how JUnit allows us to do Excepton Testing

Example 1

new ArrayList<Object>().get(0); // Array list is empty, so it should result in IndexOutOfBoundsException

  @Test(expected= IndexOutOfBoundsException.class)
    public void empty() {
         new ArrayList<Object>().get(0);
    }
So this test case would pass, if IndexOutOfBoundsException is thrown else the Test case fails

Example 2

 @Test
    public void testExceptionMessage() {
        try {
            new ArrayList<Object>().get(0);
            fail("Expected an IndexOutOfBoundsException to be thrown");
}

         catch (IndexOutOfBoundsException anIndexOutOfBoundsException) {
            assertThat(anIndexOutOfBoundsException.getMessage(), is("Index: 0, Size: 0"));
            }
    }

In this way we can not only test what Exception we get but we can also validate what message is thrown 

JUnit Assertions

Assertions is one of the most used and important part of your Framework
JUnit provides overloaded Assertions for all primitive types(ie int, string etc), Objects and Arrays(Primitive and Objects)

Syntax for Assertions
<expected_value> , <actual_value>
or
<String output for failure>, <expected_value> , <actual_value>

Examples

1)Compares if text are same
 @Test
  public void testAssertEquals() {
    org.junit.Assert.assertEquals("failure - strings are not equal", "text", "text");
  }

2)Checks if condition passed results in false, if false_var is evaluated to true then error is shown
Remember this condition can be used to optionally run your test case, if you include this in your @Before Class

  @Test
  public void testAssertFalse() {
    org.junit.Assert.assertFalse("failure - should be false", false_var);
  }

3)Checks if the obect passed is null or not, if not null, then shows error
   @Test
  public void testAssertNotNull() {
    org.junit.Assert.assertNotNull("should not be null", new Object());
  }

4)Checks if two obects are same
  @Test
  public void testAssertNotSame() {
    org.junit.Assert.assertNotSame("should not be same Object", new Object(), new Object());
  }

A slightly different assertion is assertThat, usage is

Syntax
<optional_failure_msg> , <actual_value> , <matcher_Object>

asserThat is used in the suitations, where the actual value is dynamically generated and you can use a matcher obect to verify it at run time with a pattern

Examples

1) This can be used to check your order_num pattern, date etc
 @Test
  public void testAssertThatBothContainsString() {
    org.junit.Assert.assertThat("albumen", both(containsString("a")).and(containsString("b")));
  }

2)Checks the Array List

  @Test
  public void testAssertThatEveryItemContainsString() {
    org.junit.Assert.assertThat(Arrays.asList(new String[] { "fun", "ban", "net" }), everyItem(containsString("n")));
  }

  

Monday, August 25, 2014

What is Reflection API? Advantages of Reflection API and Disadvantages of Reflection API

The Reflection API allows Java code to examine the classes and objects at run time.
The new Reflection classes allows you to call another class methods dynamically a the run time

EXAMPLE

Say you have an object of unknown type in java, you would like to call a method, dosomething on it if it exists

Static typing languages isn't really designed to support this, unless the object conforms to a known interface. But with reflection your code can look at the object and find if it has a method called dosomething and then call if it want to

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


public class Learn_reflection {


public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {


Learn_reflection t = new Learn_reflection();
Method met[] = t.getClass().getMethods();

for(int i = 0; i<met.length; i++){
if(met[i].getName().equals("Test1")){
met[i].invoke(t);
}
}
}

public void Test1() {
System.out.println("Test1");
}

public void Test2() {
System.out.println("Test2");
}

}


Advantages of Reflection API
1) Helps to look at the methods and objects at run time

DisAdvantages of Reflection API
1) Performance overload, since everything is dynamically resolved, JVM may not be able to perform certain optimizations
2)Security Restrictions : Refecion requires runtime permission to the code, which might not always be allowed

Hover Over Menu in Mozilla, IE and Chrome

There are two ways to do it

Method 1
String menuhoverlink = "//input[xpath]";
String sublink = '//input[xpath]';
Actions builder = new Actions(driver);
builder.moveToElement(driver.findElementBy(menuhoverlink).build.perform();
driver.findElementBy(sublink).click();

Method 2
IWebElement element = driver.findElement(By.XPath("urelementxpath"));
ILocatable hoverItem = (ILocatable)element;
IMouse mouse = ((IHasInputDevices)driver).Mouse;
mouse.MouseMove(hoverItem.Coordinates);
driver.findElement(By.XPath("submenuelementxpath")).Click();



StaleElementReferenceException, How to handle it??

How to deal with StaleElementReferenceException in Selenium Webdriver

What causes StaleElementException?

1)Page Refresh : A page may look like one page but in reality it may be different pages, so you might have to refind them to work with it
2)JavaScript MVC Frameworks : Many JavaScript MVC Frameworks can update the contents by rapidly tearing down and rebuilding the same elements
Example : Share prices and Graphs during market hours
4)Elements being moved : If elements disapperas of the screen and it is to be relocated, the old refrence goes stale(graphs in moneycontrol.com)
5)Elements being re-rendered : If you are working on portal, some portsal may get updated continiuosly

How to handle it ?

1)Instead of directly storing the locators, use a method to reference the element
2)Proactively wait for the element to go stale, for this you can keep a counter, say, you have button or entry when clicked or updated increment the counter(1) and re-find the element and drcrement the counter(0)
In this way, when ever you get stale element exception, stop everything, put a counter and handle it right then, This will definetly reduce the frequency of exception
This technique did work for me.
3)Use more javascript executor for such elements, not so good way to habdle but very effective

You can also refer to the below links, It has some good exmples to handle such suitation in python
 https://github.com/wiredrive/wtframework/blob/master/wtframework/wtf/utils/wait_utils.py
 https://github.com/dlai0001/selenium-tech-demo1

What is Maven? How to configure Maven in your Project

Maven is a build Automation tool for Java Projects. It addresses two aspects of building software
1)How the Software is build
2)what are its dependencies

When you create your maven project you can see the following directories getting created
Directory namePurpose
project homeContains the pom.xml and all subdirectories.
src/main/javaContains the deliverable Java sourcecode for the project.
src/main/resourcesContains the deliverable resources for the project, such as property files.
src/test/javaContains the testing Java sourcecode (JUnit or TestNG test cases, for example) for the project.
src/test/resourcesContains resources necessary for testing.
So in this way it tells how the software is to be built

Now lets see, it resolves the problem of dependcies

To manage dependencies say JUnit, all you need to do is, simply  declare JUnit project coordinates in its POM
eg :  <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>

So everytime you run your maven build it automatically downloads the version of JUnit as said in POM.xml
Next time, when you use say, 4.0 verson of Junit all you need to do is just to update a single line in your POM.xml

In this way it helps you to manage your dependencies

Steps to configure Maven in your Project

1)Download Maven Jars
2)Configure M2_HOME and path vars
3)To check if Maven is installed go to cmd prompt and type mvn --version it shd not show any error
4) Go to folder where you need to create project and type mvn archetype:generate
it will create a project
5)go to project folder and type mvn eclipse:eclipse it will create eclipse project
6) import the project to eclipse and do your coding
7) Maven will create src/test/java and src/main/java folder in src/test/java you can write all your test code
8) it will also create your pom.xml at project level
9)Update the pom.xml with maven dependencies for selenium, unit, testNG
10) go to cmd prompt and type mvn package, download all jars, it will compile and create jar file of your project
once done you can install your project directly to test env or deploy to other env directly with mvn

Maven is a industry standard way may to maintain your code be it for development/automation

You can find more information on http://maven.apache.org/index.html

Build Lifecycle of Maven 

 validate
 generate-sources
 process-sources
 generate-resources
 process-resources
 compile
 process-test-sources
 process-test-resources
 test-compile
 test
 package
 install
 deploy

Maven Integration with Eclipse

I found a good link that shows integration http://www.tutorialspoint.com/maven/maven_eclispe_ide.htm

Sunday, August 24, 2014

How to Read and Write data to excel sheet with Apache POI and NPOI

Reading and writing data to excel sheet is one of the most used feature of your Selenium framework
Here in have shown the example with Java

But remember the Steps, then you can implement the same in different languages

If you are using C#, then you can use NPOI, you can follow similar steps, it is just the .NET version of POI, here's the link https://npoi.codeplex.com/ 

Step 1) Download Apache poi jars from http://poi.apache.org/
Step 2) Add unzip the jar files and add them to your project

How to read data from excel sheet with POI API 

Algorithm
1)Open file with FileinputStream
2)Open workbook, go to sheet using sheet name
3)In the sheet go to row num and go to the cell
4)Once you reach the cell get the celltype

5)Based on what type of content is held in cell
6)Use the standard methods from POI API to read them and save the value

7)Finally return the value
-----------------------------------------------------------------------------------------

public static String getCellValue(String filePath, String sheetName, int rowNum, int cellNum) throws InvalidFormatException, IOException{


        FileInputStream fis = new FileInputStream(filePath);
        Workbook wb = WorkbookFactory.create(fis);

        int type = wb.getSheet(sheetName).getRow(rowNum).getCell(cellNum).getCellType();
        String value = "";
        if(type==Cell.CELL_TYPE_STRING){
            value = wb.getSheet(sheetName).getRow(rowNum).getCell(cellNum).getStringCellValue();  
        }else if(type==Cell.CELL_TYPE_NUMERIC){
            int numValue = (int) wb.getSheet(sheetName).getRow(rowNum).getCell(cellNum).getNumericCellValue();
            value = ""+numValue;
        }else if(type==Cell.CELL_TYPE_BOOLEAN){
            boolean boolValue =  wb.getSheet(sheetName).getRow(rowNum).getCell(cellNum).getBooleanCellValue();
            value = ""+boolValue;
        }
        return value;
    }
 

How to write data to Excel sheet with POI API 

1)Open File
2)Go to work book, go sheet, row and cell
3)Instead of get'Type'CellValue use setCellValue method and write the content to file

----------------------------------------------------------------------------------------------------

public static void writeData(String filePath, String sheetName, int rowNum, int cellNum, String value) throws InvalidFormatException, IOException{
        FileInputStream fis = new FileInputStream(filePath);
        Workbook wb = WorkbookFactory.create(fis);
        wb.getSheet(sheetName).getRow(rowNum).createCell(cellNum).setCellValue(value);
        //wb.getSheet(sheetName).createRow(rowNum).createCell(cellNum).setCellValue(value); //use this if you are writing in new row.
        FileOutputStream fos = new FileOutputStream(filePath);
        wb.write(fos);
    }


If you need more information on Apache POI or ou want to try some new features, go developers page of POI
It contains code for all your needs.. Here's the link http://poi.apache.org/spreadsheet/quick-guide.html

Welcome to Advanced Selenium Jmeter and SoapUI Blog..!!!

Hi All

Sharing knowledge has always been part of me, through this blog i would continue to do so and reach larger audience. I will be sharing a lot of Selenium Jmeter and SoapUI info, Yes, there are many blogs and sites already out there, what i will try to share is info you  would find useful on day to day basis and solutions to issues what i had faced and how I over came it
I also love algorithms, i will share some cool stuff of it as well. :-)

See you soon with my posts.

Thank you.