Friday, December 19, 2014

What is the difference between $_ and @_ variables in Perl?

Both $_ and @_ are global variables.

In a subroutine, the array @_ pass the arguments to the given subroutine
Consider the example below,

sub print
{
foreach my $arg(@_) // @_ contains, abc, xyz, lmn, It collects from call and keeps them during execution
{
print "To Print =>$arg\n";
}
}

print('abc','xyz','lmn');

Output :
To Print =>abc
To Print =>xyz
To Print =>lmn

$_ is used as a variable for the loop

foreach(1..5)
{
  print "$_\n";
}

Output
1
2
3
4
5

Combining both the features

sub print
{
  foreach(@_)
  {
    print "You passed in $_ \n";
  }
}

print('abc','xyz','1','2','true');

Monday, December 15, 2014

Perl - How to Connect to DB and Perform Insert, Update, Delete, Commit, Rollback and other some other DBI functions



DBI stands for Database Independent Interface for Perl which means DBI provides an abstraction layer between the Perl code and the underlying database, allowing you to switch database implementations really easily.

The DBI is a database access module for the Perl programming language. It provides a set of methods, variables, and conventions that provide a consistent database interface, independent of the actual database being used.

How to Conect to DB with Perl
------------------------------

#!/usr/bin/perl

use DBI
use strict;

my $driver = "mysql";
my $database = "TestDataBase";
my $dsn = "DBI:$driver:database=$database";
my $userid = "scott";
my $password = "tiger";

my $dbh = DBI->connect($dsn, $userid, $password ) or die $DBI::errstr;

If the Database connection is successful then connect will return DBI handler for futher use.
Else returns the error errstr

How to insert record in to DB with Perl
------------------------------------------

my $sth = $dbh->prepare("INSERT INTO emp
                       (FIRST_NAME, LAST_NAME, SAL )
                        values
                       ('scott', 'james', 100)"); //Prepare the sql statement
$sth->execute() or die $DBI::errstr; //Execute the statement if successful continue else return errstr
$sth->finish(); //Release the connection
$dbh->commit or die $DBI::errstr; //Commit the changes done

or

$sth = $dbh->prepare(qq{
       INSERT INTO TEST_TABLE (FIRST_NAME, AGE) VALUES (?, ?)
       });
 $sth->execute("Joe", undef);

How to insert record and pass values during runtime
----------------------------------------------------

my $first_name = "john";
my $last_name = "poul";
my $SAL = 200
my $sth = $dbh->prepare("INSERT INTO TEST_TABLE
                       (FIRST_NAME, LAST_NAME, SAL )
                        values
                       (?,?,?)");
$sth->execute($first_name,$last_name,$sal)
          or die $DBI::errstr;
$sth->finish();
$dbh->commit or die $DBI::errstr;

How to select rows from DB using Perl
---------------------------------------

my $sth = $dbh->prepare("SELECT FIRST_NAME, LAST_NAME
                        FROM emp
                        WHERE AGE > 30");
$sth->execute() or die $DBI::errstr;

print "Number of rows found :" + $sth->rows;
while (my @row = $sth->fetchrow_array()) {
   my ($first_name, $last_name ) = @row;
   print "First Name = $first_name, Last Name = $last_name\n";
}
$sth->finish();

How to update DB records using Perl
------------------------------------

my $sth = $dbh->prepare("UPDATE TEST_TABLE
                        SET   AGE = AGE + 1
                        WHERE SAL > 200");
$sth->execute() or die $DBI::errstr;

print "Number of rows updated :" + $sth->rows;
$sth->finish();
$dbh->commit or die $DBI::errstr

How to delete DB records using Perl
-------------------------------------

$age = 30;
my $sth = $dbh->prepare("DELETE FROM TEST_TABLE
                        WHERE AGE = ?");
$sth->execute( $age ) or die $DBI::errstr;

print "Number of rows deleted :" + $sth->rows;
$sth->finish();
$dbh->commit or die $DBI::errstr

Get metadata from DB using Perl
--------------------------------
This will fetch available drivers

@ary = DBI->available_drivers;
@ary = DBI->available_drivers($quiet);

get all data sources
@ary = DBI->data_sources($driver);



Sunday, December 14, 2014

How to get coordinates or dimensions of web element with Python using Selenium Webdriver

driver = webdriver.Firefox()
e = driver.find_element_by_xpath("//someXpath")
location = e.location
size = e.size
print(location)
print(size)

{'y': 202, 'x': 165}
{'width': 77, 'height': 22}

Sunday, December 7, 2014

How to download files in Mozilla using Selenium Webdriver

FirefoxProfile firefoxProfile = new FirefoxProfile();

firefoxProfile.setPreference("browser.download.folderList",2);
firefoxProfile.setPreference("browser.download.manager.showWhenStarting",false);
firefoxProfile.setPreference("browser.download.dir","c:\\downloads");
firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk","text/csv");

Here text/csv is a mime type, change this mime type depending on the file type you want to download

Popular mine types

PDF => application/pdf
Text file => text/plain
.exe => application/octet-stream
MS Doc => application/msword
xls => application/excel
.zip => application/x-compressed
.tgz => application/gnutar

How to download files in IE using Selenium Webdriver

public void clickAndSaveFileIE(WebElement element) throws AWTException, InterruptedException {

    Robot robot = new Robot();

    // Get the focus on the element..don't use click since it stalls the driver        
    element.sendKeys("");

    //simulate pressing enter          
    robot.keyPress(KeyEvent.VK_ENTER);
    robot.keyRelease(KeyEvent.VK_ENTER);

    // Wait for the download manager to open          
    Thread.sleep(2000);

    // Switch to download manager tray via Alt+N
    robot.keyPress(KeyEvent.VK_ALT);
    robot.keyPress(KeyEvent.VK_N);
    robot.keyRelease(KeyEvent.VK_N);
    robot.keyRelease(KeyEvent.VK_ALT);

    // Press S key to save          
    robot.keyPress(KeyEvent.VK_S);
    robot.keyRelease(KeyEvent.VK_S);
    Thread.sleep(2000);

    // Switch back to download manager tray via Alt+N
    robot.keyPress(KeyEvent.VK_ALT);
    robot.keyPress(KeyEvent.VK_N);
    robot.keyRelease(KeyEvent.VK_N);
    robot.keyRelease(KeyEvent.VK_ALT);

    // Tab to X exit key
    robot.keyPress(KeyEvent.VK_TAB);
    robot.keyRelease(KeyEvent.VK_TAB);

    robot.keyPress(KeyEvent.VK_TAB);
    robot.keyRelease(KeyEvent.VK_TAB);

    robot.keyPress(KeyEvent.VK_TAB);
    robot.keyRelease(KeyEvent.VK_TAB);

    // Press Enter to close the Download Manager
    robot.keyPress(KeyEvent.VK_ENTER);
    robot.keyRelease(KeyEvent.VK_ENTER);

}

How to download files in Chrome using Selenium Webdriver

//Get Chrome Driver
System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
String downloadFilepath = "/path/to/download";

//Save Chrome Preferences in Hash Map
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("profile.default_content_settings.popups", 0);
chromePrefs.put("download.default_directory", downloadFilepath);

//Save Chrome Opions
ChromeOptions options = new ChromeOptions();
HashMap<String, Object> chromeOptionsMap = new HashMap<String, Object>();
options.setExperimentalOptions("prefs", chromePrefs);
options.addArguments("--test-type");

//Set desired capability
DesiredCapabilities cap = DesiredCapabilities.chrome();
cap.setCapability(ChromeOptions.CAPABILITY, chromeOptionsMap);
cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
cap.setCapability(ChromeOptions.CAPABILITY, options);

//Start Chrome Driver
WebDriver driver = new ChromeDriver(cap);

Sunday, November 30, 2014

If there is a pop-up coming on the page for a fraction of second, and if you have to capture the text appearing on it, how would you capture it?

Answer to a question from LinkedIn

https://www.linkedin.com/groups/If-there-is-popup-coming-4285318.S.5942940576692314114?view=&item=5942940576692314114&type=member&gid=4285318&trk=eml-b2_anet_digest-hero-4-hero-disc-disc-0&midToken=AQHTpw42IOK2Ew&fromEmail=fromEmail&ut=3htuvU3cBnrSw1

If you using webdriver, then does not matter if what you see on screen or how long it actually appears
Selenium Webdriver just works on the source of your web page, Since you said it is a pop up, either it is alert msg or a javascript pop up.

It cannot be a alert since it appeard for a fraction of second and withtout user input it goes away, so it must be a Javascipt pop up.

To capture this there are two ways.
First, directly invoke the javascript from selenium and capture it seperately and then use them in your actual scipt
Second, Use any Man in the middle Software such as Fiddler(for asp .net but can be used for jsp as well) and stop the screen when the particular Javascript is called so you can capture it.

Tuesday, November 25, 2014

How to execute SoapUI Project from Command Line

SoapUI currently comes with the following command line tools for running TestCases and LoadTests

loadtestrunner.bat => To run Load test
mockservicerunner.bat => to run mock services
securitytestrunner.bat => to run security test
testrunner.bat => Used to run your soapui testcases
toolruner.bat => Runs any of the configured Code Generation tools for specified project and interface
wargenerator.bat => used to generate war files

Syntax to run command line tools is

<command line tool> <parameters> <report(optional)> <project>
eg
testrunner.bat     -FPDF     -R"Project Report"     c:\projects\my-soapui-project.xml

Another example
Here we will pass the property which will be  used in run the test

1)testrunner.bat -P username=ss123 Cc:\projects\my-soapui-project.xml
-P => Sets project property with name=value which can be used to run testsuites

2)testrunner.bat -r c:\projects\my-soapui-project.xml
-r => prints a small report in console

SoapUI 5.0.0 TestCaseRunner Summary
-----------------------------
Time Taken: 5301ms
Total TestSuites: 2
Total TestCases: 2 (1 failed)
Total TestSteps: 3
Total Request Assertions: 2
Total Failed Assertions: 0
Total Exported Results: 1

3)testrunner.bat -j c:\projects\my-soapui-project.xml
-j will create Junit style reports, the xml generated will be in the bin folder of SoapUI

4)testrunner.bat -e www.google.com  c:\projects\my-soapui-project.xml
-e => set end point url, overrides the endpoint set in the project file

5)testrunner.bat -h www.google.com:9001  c:\projects\my-soapui-project.xml
 -h => overrides only the host part of the endpoint set in the project file

Sunday, November 23, 2014

getNodeValues in XmlHolder for SoapUI

def request = '''<xml>
   <node>
      <val1>pqr</val1>
      <val2>abc</val2>
   </node>
   <node>
      <val1>xyz</val1>
      <val2>lmn</val2>
   </node>
</xml>'''


def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context )
def holder = new com.eviware.soapui.support.XmlHolder( request )


// loop item nodes in response message

//get All occurance of node/val1
log.info "--------First For loop------------"
for( item in holder.getNodeValues( "//node/val1" ))
log.info "Node : [$item]"

OUTPUT

Sun Nov 23 19:51:36 IST 2014:INFO:--------First For loop------------
Sun Nov 23 19:51:36 IST 2014:INFO:Node : [pqr]
Sun Nov 23 19:51:36 IST 2014:INFO:Node : [xyz]
Sun Nov 23 19:51:36 IST 2014:INFO:--------Second For loop------------
Sun Nov 23 19:51:36 IST 2014:INFO:Node : [pqr]

How to removenodes from Request/Response for assertion

import com.eviware.soapui.support.*
def soapmessage = '''<ns:basket xmlns:ns="http://example.com">
                    <ns:fruit>
                    <ns:name>banana</ns:name>
                          <ns:color>yellow</ns:color>
                         </ns:fruit>
                       <ns:fruit>
                          <ns:name>apple</ns:name>
                          <ns:color>green</ns:color>
                         </ns:fruit>
                       <ns:fruit>
                         <ns:name>strawberry</ns:name>
                          <ns:color>red</ns:color>
                         </ns:fruit>
                    </ns:basket>'''


def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context )

def holder = new com.eviware.soapui.support.XmlHolder( soapmessage )
  //holder.namespaces["ns"] = "http://example.com"
  //holder.declareNamespace("ns", "http://example.com")

assert holder.getNodeValue("//ns:fruit[2]/ns:color[1]") == "green"

holder.removeDomNodes("//*:fruit[2]")

assert holder.getNodeValue("//ns:fruit[2]/ns:color[1]") == "red"
log.info "Done"

How to access property in Script Assertion in SoapUI using Groovy Script

//Set Property
messageExchange.modelItem.testStep.testCase.setPropertyValue("MyProp", someValue)

//Get Property
def testCaseProperty = messageExchange.modelItem.testStep.testCase.getPropertyValue("MyProp")

Setting and Getting properties at all levels in SoapUI with Groovy Script

Getting Properties…

-From a Groovy Script test step
def testCaseProperty = testRunner.testCase.getPropertyValue("MyProp")
def testSuiteProperty = testRunner.testCase.testSuite.getPropertyValue("MyProp")
def projectProperty = testRunner.testCase.testSuite.project.getPropertyValue("MyProp")
def globalProperty = com.eviware.soapui.SoapUI.globalProperties.getPropertyValue("MyProp")

Setting Properties…

-From a Groovy Script test step:
testRunner.testCase.setPropertyValue("MyProp", someValue)
testRunner.testCase.testSuite.setPropertyValue("MyProp", someValue)
testRunner.testCase.testSuite.project.setPropertyValue("MyProp", someValue)
com.eviware.soapui.SoapUI.globalProperties.setPropertyValue("MyProp", someValue)

How to save all Test Case properties in a Map using Groovy Script

def tcProps = testRunner.testCase.getProperties()
def map = [:]

//grab all the properties from the test case and put them in a map as long as they aren't empty
for(p in tcProps){    
            if (p.value.getValue() != "") {
            map.put(p.key, p.value.getValue())            
    } 
}

XML Parser in SoapUI

def studentRecords = ''' 
        <students> 
              <student name='sname' id='sid' college='collegename' /> 
        </students> 
    ''' 
def records = new XmlParser().parseText(studentRecords) 
def requiredMap = records.student[0].attributes()


log.info "entrySet() shows name value pairs ==> "+requiredMap.entrySet()
// An EntrySet is just a thin wrapper providing a view of objects that already exist inside the HashMap
log.info "keySet() shows only keys ==> "+requiredMap.keySet()
log.info "containsKey, check if id tag is present ==> "+requiredMap.containsKey("id")
log.info "conatinsValue, check if id tag VALUE is present ==> "+requiredMap.containsValue("sid")
log.info "get value of the key id ==> "+requiredMap.get("id")
log.info "check if map is empty ==> "+requiredMap.isEmpty()
log.info "add value to map ==> "+requiredMap.put("sagar" , "singh")
log.info "entrySet() values are ==> "+requiredMap.entrySet()
//log.info "remove from map ==> "+requiredMap.remove("sagar")
//log.info "entrySet() values are ==> "+requiredMap.entrySet()

OUTPUT

Sun Nov 23 19:11:59 IST 2014:INFO:entrySet() shows name value pairs ==> [name=sname, id=sid, college=collegename]
Sun Nov 23 19:11:59 IST 2014:INFO:keySet() shows only keys ==> [name, id, college]
Sun Nov 23 19:11:59 IST 2014:INFO:containsKey, check if id tag is present ==> true
Sun Nov 23 19:11:59 IST 2014:INFO:conatinsValue, check if id tag VALUE is present ==> true
Sun Nov 23 19:11:59 IST 2014:INFO:get value of the key id ==> sid
Sun Nov 23 19:11:59 IST 2014:INFO:check if map is empty ==> false
Sun Nov 23 19:11:59 IST 2014:INFO:add value to map ==> null
Sun Nov 23 19:11:59 IST 2014:INFO:entrySet() values are ==> [name=sname, id=sid, college=collegename, sagar=singh]
Sun Nov 23 19:11:59 IST 2014:INFO:remove from map ==> singh
Sun Nov 23 19:11:59 IST 2014:INFO:entrySet() values are ==> [name=sname, id=sid, college=collegename]

How to transfer property proerty to all Test Cases in Test Suite an access it

Transfer property to all TC

def ABC = testRunner.testCase.testSuite.project.getTestSuiteList()
def DEF = testRunner.testCase.testSuite.getPropertyValue("w2_SessionID")

for (testSuite in ABC){
for (testCase in testSuite.getTestCaseList()){
testCase.setPropertyValue("w2_SessionID", DEF)
}
}


Access property in each Test Case

def abdProjProp = context.expand( '${#Project#abdProjProp}' )

How to run a TestCase located in another project

def prj = testRunner.testCase.testSuite.project.workspace.getProjectByName("ProjectName")

2.tCase = prj.testSuites['TestSuiteName'].testCases['TestCaseName']

3.tStep = tCase.getTestStepByName("TestStepName")

4.def runner = tStep.run(testRunner, context)

How to transfer properties between projects

//get test case from other project
project = testRunner.getTestCase().getTestSuite().getProject().getWorkspace().getProjectByName(project_name)
testSuite = project.getTestSuiteByName(suite_name);
testCase = testSuite.getTestCaseByName(testcase_name);

//set properties
testRunner.testCase.setPropertyValue(property_name, property_value);
testRunner.testCase.setPropertyValue(another_property_name, another_property_value);

// run test case
runner = testCase.run(new com.eviware.soapui.support.types.StringToObjectMap(), false);

Groovy Script to transfer Property in SoapUI

// get request property
def request = testRunner.testCase.getTestStepByName( "teststepname" )
def property = request.getProperty( "request" )

// set request property
request = testRunner.testCase.getTestStepByName( "newteststep" )
request.getProperty("request").setValue(property.getValue())

What are the common assertions used in API Testing

1)Check response status
2)Assert values saved in DB
3)Compare values between request xml and data saved in DB
4)Time taken for response
5)Check xpaths
6)Check the expected tag value
7)Assert response xml with wsdl

And lots more..

Contains() and starts-with() function in Xpath

Certain sites like Google and Yahoo have dynamic attributes,

Eg : <input id="text-12345" />
next time when you try to run in a new sesion the same tag will have the values <input id="text-12567" />
Here 12567 is dynammically generated everytime a new session is created

To handle such dynamic attributes we can use certain Xpath functions like 'starts-with' and 'contains'

tag => <input id="text-12345" />
xpath => //input[starts-with(@id, 'text-')]

When you use starts-with, a part of xpath should remain same and other part will be dynamically generated.

What if the complete xpath is dynamically generated? In this case you cannot automate for external website, whereas if your company owns the site then you can talk to developer and get the script which dynamically generates the xpath and use in your program

contains Xpath functions

Consider the tag
tag => <span class="top heading bold">
Xpath => //span[contains(@class, 'heading')]

Contains is used when an element can be located by a value that could be surrounded by other text, the contains function can be used.

Better way of writing the same would be with CSS selectors
xpath => //div[contains(@class, 'article-heading')]
CSS => css=div.article-heading

For complex xpaths or compound xpaths

Compound Xpaths => //ul[@class='featureList' and contains(li, 'Type')]

Saturday, November 22, 2014

How to Disable teststep within a test case in SoapUI with groovy script

def totalTestCases = testSuite.getTestCaseCount();
for(n in (0..totalTestCases-1)) {
    if (testSuite.getTestCaseAt(n).getTestStepByName("MyTestStep")){
        testSuite.getTestCaseAt(n).getTestStepByName("MyTestStep").setDisabled(true)
    }
}

Print Testcase name and Teststep names in SoapUI with Groovy Script

import com.eviware.soapui.impl.wsdl.teststeps.*
def i=0;
for( testCase in testRunner.testCase.testSuite.getTestCaseList() ) {
    for( testStep in testCase.getTestStepList() ) {
        if( testStep instanceof WsdlTestRequestStep ) {
        log.info i++ +"Name of testcases in this suite: " +"[" +testCase.getLabel() +"]" +" Name of the
        WSDL step is " +testStep.getName();
        }
    }
}

Constructors For XmlHolder

XmlHolder is the class provided by SoapUI to parse the Xml


1)def holder = XmlHolder(Node node)
Here were are passing the node directly

eg : def holder = XmlHolder("//parent/child")

2)def holder = XmlHolder(String Xml)
Here we are directly passing the xml itself

eg : def holder = XmlHolder("<body><name>xyz</name><phone>1234567890</phone></body>")

3)def holder = XmlHolder(org.apache.xmlbeans.XmlObject xmlObject)
here we pass an obect that has xml in it

How to access Nodes Using XmlHolder in SoapUI API

import com.eviware.soapui.support.*

def request='''
<Body>
<keyboard1>Qwerty~12-qwerty</keyboard1>
<conversationId1>sfksjkdjf2213123</conversationId1>
</Body>
'''

XmlHolder holder = new XmlHolder(request)
log.info holder.getNodeValue("//keyboard1")

Sunday, October 19, 2014

Logic Controllers Jmeter

Logic Controllers

Logic Controllers determine the order in which Samplers are processed.

1)Loop Controller

If you add a Loop Controller, JMeter will loop through them a certain number of times, in addition to the loop value you specified for the Thread Group.

For example, if you add one HTTP Request to a Loop Controller with a loop count of two, and configure the Thread Group loop count to three, JMeter will send a total of 2 * 3 = 6 HTTP Requests.

2)Once Only Controller
The Once Only Logic Controller tells JMeter to process the controller(s) inside it only once per Thread, and pass over any requests under it during further iterations through the test plan.

The Once Only Controller will now execute always during the first iteration of any looping parent controller. Thus, if the Once Only Controller is placed under a Loop Controller specified to loop 5 times, then the Once Only Controller will execute only on the first iteration through the Loop Controller (ie, every 5 times).

More to come..

Monday, September 8, 2014

Scrum Process Flow

1)Set Up 
a)Set up the environment for Agile, in Rally or Jira
b)Activate the Agile plugins
c)Assign scrum roles and access to the teams

2)Create Product
a)It is list of Prioritized requirements 
b)You can use excel. post it on walls or filpchart to store product backlogs

3)Create User stories
a)A user story is a brief statement of a product requirement or a customer business case created by a product owner
b)Discuss user stories with development team, distribute work to team, create tasks in Rally/Jira tools
c)Define ready and done meaning

4)Create Release
a)A release has a start and end date during which a number of development iterations are completed. 
b)When a release record is created, at least one scrum team and its members should also be created

5)Create a Sprint
a)A sprint is the basic unit of time in the development process. A sprint can be of any length, but typically takes between one and four weeks to finish. 
b)The scrum master creates one or more sprints from within a release. 
c)All sprints within a release must fit within the release start and end dates.

6)Plan the sprint
a)the team and scrum master decide on what stories they can commit to completing within a sprint
b)The scrum master must make sure that the effort (story points) required to complete the stories matches the capacity of the release team
c)A velocity chart is available to help in the estimation process

7)Track sprint Progress
a)The scrum master manages the sprint team's efforts, provides progress reports, and removes any impediments that the team encounters
b)Team members update task and story records and conduct daily stand-up meetings (scrum meetings) to communicate their progress and concerns to the scrum master

8) Generate Charts
a)Use charts
b)Use burn chart chats
c)Use velocity charts

Agile Retrospective


1)Share lesson learnt
2)Generate common sights
3)Bring improvements into the team
4)Uncover the conflicts
5)Correct dysfunctional behavior

When should be restrospective to be held
1)After the sprint
2)After important milestome
3)At the end of project

Scrum of Scrums


1)Scrum of scrums are meeting between different scrum master across the teams invloved in the project
2)ideally dialy they should meet, but 2-3 times a week is good
3)Discuss issues that could create impediments to other scrum teams
4)All teams must begin and end sprint on same day, discuss what impediments might occur to  meet the dates

How to conduct Sprint Review


1)The scrum master opens the meeting
2)The team presents the results
a)The stakeholders offer opinions and the feed back
b)The product owners accept the results
c)The product owners records new ideas and insights and open issues to update the product backlog
3)The scrum master states the velocity, recapitulates the insights and thanks all participants and announces next meeting
a)Retrospective and Sprint planning
b)Date and venue of the next sprint

Controlling and Reporting in Agile


a)Feed back loops in Scrum
1)Daily : Evaluating the remainin work and updating the sprint burn down chart
2)Sprint : The team velocity during the sprint and updating the sprint burn down chart after the realase plan
3)Release: Deploying value to customer

Reports in Scrum
You can use tools like Rallyand Jira for it
1)Sprint burn down chart : Shows the total remaining effort for the team
Additional variations are, counting open tasks and open user stories
2)Sprint end Report : Complied by scrum master, contains, start and end date of sprint, product backlogs, sprint backlogs, impediments open and closed, Story points delivered
3)Task board : List of taks for each sprint, marked completed or pending
4)Release Burn down chart
5)Velocity Diagram

Conducting Daily Scrum


1)Everyday day at the same time and place
2)Insist that it begins on time
3)Keep it to the time box of 15mins
4)Only scrum team members must speak

what to achieve from Daily Scrum
1)Each team team must answer exactly three questions
what i have done since last meeting
what i wil do until next meeting
what impedements i have 
2)All team members must participate dialy 

After the Daily Scrum
1)Scrum master works in removing the impediments 
2)When additional questions come, like technical issues, schedule addtional metings

Tracking the process
1)At the end of dialy scrum, the sprint backlog must be updated and burn down chart must be updated
2)after the meeting,discuss the adaptations with product owner 

The Dialy Scrum


1)Each team members should know what the other team members are doing and what they have achieved
2)Each team member must report report about his/her work in enough details to make it transperant to others 
3)The dialy scrum is akey part of inspect and adapt

Sprint backlogs


1)Suring sprint, the product backlogs are broken into tasks, and any pending taks fron the sprint becomes the sprint backlog 
2)It is a living artifact
3)Team tracks this remaning effort unttil remaining effort is zero

Sprint Goals


1)The sprint goal always represent a potentially shippable product contaning new valuable business functionality 
2)This keeps teams focus on value creation
3)It keeps stakeholders supportive of the project

How to determine sprint velocity


1)Execute 2-3 sprints and measure the velocity
2)Use historicle data to make an estimate of the velocity 
3)perform a simulated sprint and estimate how much can be delivered in a sprint

What is Good User story


A good User story must be
1)Independent
2)Negotiable
3)Verticle
4)Estimable
5)Small
6)Testable

User story, Structure of User Story


1)User story describes business scenario in natural language
2)It is intentionally short and does not cover all details
3)it represents the feature to be implemented

Structure of User Story
As a.. (role : who wants something)
I want.. (What : business reqs)
because.. (Why: benifits, business value)

Product backlog


1)It is list of Prioritized requirements
2)You can use excel. post it on walls or filpchart to store product backlogs

Requirements in Scrum


1)In scrum collecting requirements and realiing of requirements overlaps, they are not seperate processes
2)Requirements in Scrum are emergent, ie, existing requirements change and new reqs are discovered

Team Charter


1)Team charter is a working Agreement of the Team 
2)It contains basic information, as to, what softwares will be used, what tools will be used, what are the cimmunication rules, What are the commitments
3)It will define what is ready and done means
4)In case it is very large project it can be a seperate document

Benifits and Pitfalls of Team Charter
1)It helps to uncover ambigious project goals
2)It helps team to develop common understand of their work and to develop good working relations
3)It can also be common activities for a new team 
4)Keep it short 

Who qualifies to be a Scrum Master


1)He should be able to effiectively prganise the meeting
2)He should be able to find techniques to develop the team creativity 
3)He should be able to helps team to develop
4)He should be able to help individual team member to exploit their potential
5)He should help team to continiously improve the work

Scrum Team

The Development Team 
1)Self Organizing 
2)IDEALLY full time they are dedicated for sprint 
3)Selects the requirement that is to be realized in a sprint and commits to the sprint goal
4)Collectively reponsible for meeting this commitment and demonstarting the new product increment at the end of the sprint

Role of product Owner 
1)Defines product features and resolves open requirement and business issues
2)Accepts or reects the results 
3)He is responsible for ROI of the product 
4)Determines delivery date and scope of the product 
5)Priorities the features depending on teir value and the assiciated risk

Scrum Master
1)Scrum master ia s servant leader
2)His strength is lack of power
3)For a new team, being scrum master is a full time job 
4)Coaches team and product owner
5)Removes impediments 
6)Ensures compliance with Scrum values and principles
7)Protects team from external disturbances
8)Removes impediments 

Scrum Roles


1)Product owner : Defines the product, he is responsible for the results
2)Scrum Master : Removes impediments, He is responsible for process
3)Team(Development Team) : Self organising(Both Dev and QA), They are responsible for releasing the product imcrement
4)Others Stakeholder : They speak with product owner and scrum naster for all details regarding the sprint and project as the whole

Scrum Flow


1)The product owner is responsible for creating and prioritising the product backlog, a dynamic list for the product 
2)Before each sprint, team meets and discusses how many highest proirity tasks they can deliver during the sprint
3)During the sprint, team meets in daily scrum call and follows progress in burn down chart
4)The Scrummaster coaches the team, removes impediments and ensures that team is able to work effectively
5)During sprint valuable functionality is developed and a potentially shippable product is incrementally developed
6)At end if sprint, team holds a retrospective meeting and identifies how they can work together more effectively during the next sprint

Agile Principles

1)Highest priority is to satisfy the customer through early and continuous delivery of valuable software
2)Welcome changes in requirements even late in dev cycle
3)Developer and business people must work together through out the project
4)The most effective and efficient way of conveying information is Face to face conversation 
5)Working software  is the primary measure of progress

Friday, September 5, 2014

How to Connect to DB in SoapUI with Groovy Scripting

1)import groovy.sql.Sql : Import the SQL package

2)def request = context.expand('${TC_Name#request}')
def holder = new XmlHolder(request)
OrderNum = holder.getNodeValue("//v1:tagname")
log.info OrderNum  : This will hold the request that is being received from the down stream application with the order number

3)getNodeValue() : This will get the tag value of the xpath passed

4) def dbUrl="jdbc:oracle:thin:@tqwertrxx.vxc.abc.com:15xx:tqwetrxx"
def dbUsername="abc"
def dbPassword="abcc#xxxx"
def dbDriver="oracle.jdbc.driver.OracleDriver"
def db = Sql.newInstance(dbUrl , dbUsername , dbPassword , dbDriver)
// Connect to DB

5) def q1 = "select order_id from order where order_name = $OrderNum“
// Writing the query and passing a variable to it, remember to put the dollar sign to make groovy understand that it is a variable

6) result = db.rows(q1) : This will execute the query and return the LIST of data returned from DB in a LIST format

7) result.get(0).get("order_id") // This means, from the 0th col get the value of order_process_status_id
Similarly if the query returns 2 rows then to access the second row we write result.get(1).get("order_id")

8)Once the row from DB are retrieved use them to perform any type of assertion that is required

Risks Addressed Through Performance Testing

Speed related risks

Ensure that your performance requirements and goals represent the needs and desires of your users,

Compare your speed measurements against previous versions and competing applications.

Design load tests that replicate actual workload at both normal and anticipated peak times.

Conduct performance testing with data types, distributions, and volumes similar to those used in business 
operations during actual production

Include time-critical transactions in your performance tests.

Validate that all of the correct data was displayed and saved during your performance test.

Scalibility Related Risks

Compare measured speeds under various loads.

When you find a scalability limit, incrementally reduce the load and retest to help you identify a metric that can serve as a reliable indicator that the application is approaching that limit in enough time for you to apply countermeasures

Conduct performance tests beyond expected peak loads and observe behavior by having representative users and stakeholders access the application manually during and after the performance test.

Validate the functional accuracy of the application under various loads by checking database entries created or validating content returned in response to particular user requests.

Stability Related Risks

Take a server offline during a test and observe functional, performance, and data-integrity behaviors of the remaining systems.

Include error or exception cases in your performance test scenarios (for example, users trying to log on with improper credentials

Apply a patch to the system during a performance test

Force a backup and/or virus definition update during a performance test.

Make time for realistic endurance tests 

Source : Various websites

Baseline and BenchMarking

Baseline : Creating a baseline against which to evaluate the effectiveness of subsequent performance-improving changes to the system or application will generally increase project efficiency.


Benchmarking : is the process of comparing your system’s performance against a baseline that you have created internally or against an industry standard endorsed by some other organization.

Source : Various websites

Categories of performance testing


Performance testing : Performance is concerned with achieving response times, throughput, and resource-utilization levels that meet the performance objectives for the project or product

Load testing : Validating performance characteristics of the system or application under test when subjected to workloads and load volumes anticipated during production operations

Stress testing : Validating performance characteristics of the system or application under test when subjected to conditions beyond those anticipated during production operations. Stress tests may also include tests focused on determining or validating performance characteristics of the system or application under test when subjected to other stressful conditions, such as limited memory, insufficient disk space, or server failure. 


Source : Various websites

What is Performamce tuning??


When end-to-end performance testing reveals system or application characteristics that are deemed unacceptable, many teams shift their focus from performance testing to performance tuning,


When the tests reveal performance characteristics deemed to be unacceptable, the performance testing and tuning team enters a diagnosis and remediation stage (tuning) that will require changes to be applied to the test environment and/or the application. 


Source : Various websites

Why we do performance testing??

Why we do performance testing??


1)For Assessing release readiness
Helps sstakeholders who make decisions about whether an application is ready for release for handling future growth, or whether it requires a performance improvement/hardware upgrade prior to release

2)For Assessing infrastructure adequacy
Determining the capacity of the application’s infrastructure, as well as determining the future resources required to deliver acceptable application performance
Verifying that the application exhibits the desired performance characteristics, within budgeted resource utilization constraints.

3)For Assessing adequacy of developed software performance
Determining the application’s desired performance characteristics before and after changes to the software.

4) For Improving the efficiency of performance tuning
Analyzing the behavior of the application at various load levels.
Identifying bottlenecks in the application. 

Source : Various Websites

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