Sunday, November 25, 2012

Performing fireEvent in WebDriver

WebElement element = driver.findElement(By.id("myElement"));
JavascriptLibrary javascript = new JavascriptLibrary();
javascript.callEmbeddedSelenium(driver, "triggerEvent", element, "blur");

Ref:https://groups.google.com/forum/?fromgroups#!topic/selenium-users/jk59XG2TQk8

Saturday, November 17, 2012

window.showModalDialog - Webdriver Issue

Last month I was automating a scenario where the popup window showsup with Yes/No button. While verifying manually i thought it can be handled either by using Alert / selectWindow and perform actions.
At first I tried to record the same scenario using Selenium-IDE
Unfortunately IDE is not able to recognize the window :(.

So I thought to verify how the popup window was actually called/invoked.
- On click a button , it popups the child window and the main window is still waiting to complete its transcation.
-  Webdriver's driver will be waiting for its turn to complete the transcation , and not able to execute the statements until i close the popup manually. (In IE with selectWindow.. worked , but in Firefox ..NO).
-I verified the button using firebug , and the html code was something like <... onclick="return mypopup('Click Yes if you need to continue')"....>
-And in the mypopup javascript code is using window.shwoModalDialog
-For me I need to click Yes , and the application is actually returning true. if No, returns false.

So finally I written a piece of code which updates the the HTML code in the app at run time using.

public void clickElementAndConfirmPopup(){
WebElement element =  ..findElement.....
((JavascriptExecutor) DriverFactory.getDriver()).executeScript(
"arguments[0].setAttribute('onclick',arguments[1]);", element, "return true");
element.click(); } public void clickElementAndConfirmPopup(){

WebElement element = ..findElement.....
((JavascriptExecutor) DriverFactory.getDriver()).executeScript(
"arguments[0].setAttribute('onclick',arguments[1]);", element, "return false");
element.click();
}

- And now able to handle in both browsers (IE and FireFox)..



Friday, October 26, 2012

Memory Leak Analyzer (Got java.lang.RuntimeException: java.lang.OutOfMemoryError: Java heap space)

One fine morning my client was asked me to develop an a small Framework as per his needs. And I started writing code in Java which drives lot of excel files , xmls etc. Due to emergency I delivered  code to accomplish the immediate needs and knowing that it may have some memory leaks which I need to fix and which is my next immediate high priority one.

So I used MAT to find and analyze the code. And found it was really a cool plug-in.
1. How to install MAT plugin
Install plugin from - http://download.eclipse.org/mat/1.2/update-site/
2. MAT generates .hprof file , how to get it.
In Run-Configuration , under Argument tab in VM argument section added
    -XX:+HeapDumpOnOutOfMemoryError
3. If .hprof file is too big?
Add -vmargs -XX:PermSize=256m -XX:MaxPermSize=256m -Xms256m -Xmx1024m into eclipse.ini
4.How to open .hprof in Eclipse.
 Open MAT perspective , and File->Open Head Dump and Open .hprof generated in the project.
5.Analysis....

 

Tuesday, October 16, 2012

WebDriver - How to run tests on InternetExplorer

1. Download IEDriverServer from http://code.google.com/p/selenium/downloads/list
2.Create WebDriver instance as follows
WebDriver localDriver=;

capability = DesiredCapabilities.internetExplorer();
capability.setJavascriptEnabled(
true);
capability.setCapability(CapabilityType.

TAKES_SCREENSHOT, true);
capability.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
capability.setCapability(CapabilityType.
SUPPORTS_JAVASCRIPT, true);
capability.setCapability(InternetExplorerDriver.
INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
try {
localDriver.setDriver(new RemoteWebDriver(new URL("http://127.0.0.1:5555"), capability));
localDriver.getDriver().manage().timeouts().implicitlyWait(30, TimeUnit.

SECONDS);
}
catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();

}
3. In your testcase method use localDriver
4. Run IEDriverServerxxx.exe
5. Run your tests.

Wednesday, August 1, 2012

10 Commandments for Test Automation Outsourcing

http://shrinik.blogspot.in/2008/09/10-commandments-for-automation.html

Here is an outline .. read complete details in the actual blog.
Automation is not an answer to your testing problems
Automation is White Elephant
Anything that is quickly creatable – is quickly perishable
Your business users can not create and own Automation solutions
Judge your vendor by the questions they ask about automation Higher % of offshoring in automation higher investments to make
Pay attention to dependencies and Quality of current test Artifacts
Decide Acceptance criteria
Avoid linking an automation project (and its deliverables) to application release dates
Record and Playback (RP) Automation is for Kids

Do you agree with these commandments? Any different experience?

[update]
Some additional tips :
What a Vendor should ask you
- questions about your manual testing practice
- Your objectives of Automation and expectations
- Readiness to take up automation in terms of test cases, application state and environment
- Ask about your expectations on ROI

What vendor should suggest you
- Plan for automation maintenance when supplier is gone.
- Automation may or may not reduce cycle time – that depends upon nature of tests, application technology stack, nature of tool etc
- Automation may or may not reduce the cost of testing.

What to look for in an automation proposal
- Acceptance criteria
- Automation design details – how tests will be structured
- Environment related assumptions
- Pre-requisites about tool licenses, test cases, test data, access to developers, testers and business users (for clarifications about test cases)

Wednesday, March 14, 2012

How to get the Element type in Selenium

Below command can be used to get the Element type i.e input,textarea,select..etc
selenium.getEval(String.format("this.browserbot.getCurrentWindow().document.getElementById('%s').type", ElementId)

Friday, March 2, 2012

Session Data loss popup problem

I want to share one of my experiences in how easy to maintain scripts when we follow Page Object pattern with a recent change in one of the application.

To avoid data loss while navigating or refreshing to a page, a popup window appears with message "Application session / Data will be loss" with OK and Cancel button. (And which is not a JavaScript popup :( )
Problem:

There are too many flows where the application opens dialog boxes, frames, popup etc.
Everywhere we need to handle the Session popup.

Solution: When we view the source code of the page, we got to know the JavaScript for Session popup written as below

&lt script language="JavaScript" &gt

var allowPrompt = true;

window.onbeforeunload = confirmExit;
.....
So, to avoid this we used  ”this.browserbot.getCurrentWindow().allowPrompt=false"  command in our base page constructor which solved the problem.
Now we are happily running our tests without any change in our test script(s).

Wednesday, January 18, 2012

Python - Paramiko - Transport to negotiate SSH2 across the connection

Recently i got a task , where i need to connect to linux box,copy some files and run some shell scripts before i am going to validate my UI using selenium in my windows box.
I felt both are good to use
1. Python - paramiko
2. sshxcute

I want to share w.r.t paramiko,as for #2 , there are good examples available in the same site/page.


import paramiko
import ConfigParser
from config import *
import glob
import os
import md5


global ssh
dir_local = 'c:\paramikoLearn'
dir_remote = "/home/test"
filePattern = "*.txt"
 
def connectTo():
     ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
     ssh.connect(HOSTNAME, username=USERNAME, password=PASSWORD)

def closeConnection():
    ssh.close();
   

def copy():

# Get paramiko Transport to negotiate SSH2 across the connection  

    try:
        t = ssh.get_transport()
        print "Start client"
     
        if not t.is_authenticated():
            print "Connect Client"
            t.connect(username=USERNAME, password=PASSWORD)
            t.connect
            print "StartClient successful"
        else:
            sftp = t.open_session()
            print "StartClient successful"
       
        sftp = paramiko.SFTPClient.from_transport(t)
       
        # BETTER: use the get() and put() methods
        # for fname in os.listdir(dir_local):
       
        for  fname in glob.glob(dir_local + os.sep + filePattern):
            is_up_to_date = False
            if fname.lower().endswith('txt'):
                local_file = os.path.join(dir_local, fname)
                remote_file = dir_remote + '/' + os.path.basename(fname)
       
                #if remote file exists
                try:
                    if sftp.stat(remote_file):
                        local_file_data = open(local_file, "rb").read()
                        remote_file_data = sftp.open(remote_file).read()
                        md1 = md5.new(local_file_data).digest()
                        md2 = md5.new(remote_file_data).digest()
                        if md1 == md2:
                            is_up_to_date = True
                            print "UNCHANGED:", os.path.basename(fname)
                        else:
                            print "MODIFIED:", os.path.basename(fname),
                except:
                    print "NEW: ", os.path.basename(fname),
       
                if not is_up_to_date:
                    print 'Copying', local_file, 'to ', remote_file
                    sftp.put(local_file, remote_file)
                   
        t.close()
   
    except Exception as e:
        print '*** Caught exception: %s: %s' % (e.__class__, e)
        try:
            t.close()
        except:
            pass
   
def executeShellScript():
   return ssh.exec_command("ls -l")


if __name__ == '__main__':
   
    ssh = paramiko.SSHClient()
    try:
        connectTo()
        output = executeShellScript()
        print output[1].read()
        closeConnection()
       
    except:
        closeConnection()
    ************
In my junit testscript by using RunTime,Process i was able to run the python script and able to complete the task. :)
   

Wednesday, January 4, 2012

How to find the differences between two xml files

When i was struggling with  comparing two xml files by writing lot of Code , i came to know about XMLUnit.
Take a look at this cool code ( copied from http://xmlunit.sourceforge.net/api/overview-summary.html)
XMLUnit provides extensions to the JUnit framework to allow assertions to be made about XML content.

Using XMLUnit

  1. Create a subclass of XMLTestCasesomething like this:
    public class TestSomething extends XMLTestcase {
        // standard JUnit style constructor
        public TestSomething(String name) {
            super(name);
        }
        // standard JUnit style method
        public static TestSuite suite() {
            return new TestSuite(TestSomething.class);
        }
    }
    
  2. Set the global JAXP settings in XMLUnitso that your chosen parser and transformer are used for the tests.
    Note:You can skip this bit if you use the default JAXP settings or you have an Ant task that uses-D JVM options to specify the JAXP settings.
    // set the JAXP factories to use the Xerces parser
        // - declare to throw Exception as if this fails then all the tests will
        // fail, and JUnit copes with these Exceptions for us
        public void setUp() throws Exception {
            XMLUnit.setControlParser(
                "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
            // this next line is strictly not required - if no test parser is
            // explicitly specified then the same factory class will be used for
            // both test and control
            XMLUnit.setTestParser(
                "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
    
            XMLUnit.setSAXParserFactory(
                "org.apache.xerces.jaxp.SAXParserFactoryImpl");
            XMLUnit.setTransformerFactory(
                "org.apache.xalan.processor.TransformerFactoryImpl");
        }
    
  3. Add test methods to make your assertions: theXMLTestCase javadoc lists the available assertion methods and their usage, but here are some examples...
    public void testObjectAsXML() throws Exception {
            String expectedXML = "....";
            String objectAsXML = null;
            //...set up some object here and serialize its state into
            //our test String...
            assertXMLEqual(expectedXML, objectAsXML);
        }
    
        public void testTransformToFormatB() throws Exception {
            String expectedFormatB = "....";
            String formatA = "....";
            String transformXSLT = "....";
            Transform formatAToFormatB = new Transform(formatA, transformXSLT);
            assertXMLEqual(new Diff(expectedFormatB, formatAToFormatB), true);
        }
    
        public void testIsValidAfterTransform() throws Exception {
            String incomingMessage = "....";
            String toSourceSystemXSLT = "....";
            Transform transform = new Transform(incomingMessage, toSourceSystemXSLT);
            assertXMLValid(transform.getResultString());
        }
    
        public void testXpaths() throws Exception {
            String ukCustomerContactPhoneNos = "//customer[@country='UK']/contact/phone";
            String customerExtract1 = "....";
            String customerExtract2 = "....";
            assertXpathsNotEqual(ukCustomerContactPhoneNos, customerExtract1,
                ukCustomerContactPhoneNos, customerExtract2);
        }
    
        public void testXpathValues() throws Exception {
            String firstListItem = "/html/body/div[@id='myList']/h1/ol/li[1]";
            String secondListItem = "/html/body/div[@id='myList']/h1/ol/li[2]";
            String myHtmlPage = "....";
            assertXpathValuesNotEqual(firstListItem, secondListItem, myHtmlPage);
        }
    
        public void testSpecificXpath() throws Exception {
            String todaysTop10 = "count(//single[@topTen='true'])";
            String playlist = "....";
            assertXpathEvaluatesTo("10", todaysTop10, playlist);
    
        }
    

Selenium2 webelement.click is not working in Internet Explorer

There is some issue with few versions of IE (includes OS).
we can use webelement.sendKeys("\n") instead of webelement.click();