Saturday, April 11, 2015

How to Read and Encode an Image file using Groovy in SoapUI

Make sure all the Groovy GDK ars are present in SoapUI/Lib folder

def s = 'Any tag value which has Base64 encoded image'
String encoded = s.bytes.encodeBase64().toString()
assert 'QXJnaCwgR3Jvb3Z5IHlvdSBzYXksIG1hdGU/' == encoded
byte[] decoded = encoded.decodeBase64()
assert s == new String(decoded)

Sunday, February 15, 2015

Execute Stored procedure in SoapUI using Groovy Script

try
{
   sql.call("call stored_proc.name('111', '222', 'xxx');")
}catch (Exception ex)
{
   log.info ex.message
}catch (Error er)
{
   log.info er.message
}

Run test step depending on status of a different test step in SoapUI using Groovy Script

testRunner.testCase.testSuite.project.name
import com.eviware.soapui.model.testsuite.TestStepResult.TestStepStatus
import com.eviware.soapui.impl.wsdl.WsdlTestSuite
import com.eviware.soapui.impl.wsdl.teststeps.WsdlTestStep


myTestStepResult = testRunner.testCase.testSuite.getTestCaseByName("testCase_1").getTestStepByName("testStep_2").run(testRunner, context)
myStatus = myTestStepResult.getStatus()
if (myStatus == "OK")
testRunner.gotoStepByName("testStep_3")
else{
def tCase = testRunner.testCase.testSuite.testCases["Name of test cases"]
def tStep = tCase .testSteps["test step you want to run"]
tStep.run(testRunner, context)
}

List Names of Test cases in Test Suite in SoapUI using 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();
        }
    }
}

Wednesday, February 4, 2015

How to handle alert and confirm boxes and avoid the Race Condition

Method 1
-----------
Alert alert = null;
Wait<WebDriver> wait = new WebDriverWait(driver, 10, 50);
try {
   alert = wait.until(ExpectedConditions.alertIsPresent());
} catch (TimeoutException ignored) {
}
if (alert != null) {
   alert.accept(); // this line throws the exception
}

Method 2
-------------

public void clickOkOnAlertDialog(String dialogText) {

        Sync sync = Sync.start(20);
        while (sync.continueWaiting()) {
            wait = new WebDriverWait(driver, pageTimeoutInSeconds);
            wait.until(ExpectedConditions.alertIsPresent());
            Alert statusConfirm = driver.switchTo().alert();
            junit.framework.Assert.assertEquals(dialogText, statusConfirm.getText());
            try {
                statusConfirm.accept();
                return;
            } catch (WebDriverException e) {
                sync.sleep(250);
            }
        }
        throw new TimeoutException("Unable to locate and dismiss alert dialog: " + dialogText);
    }
   
Method 3 (Not a good way though)
-----------

((JavascriptExecutor) driver).executeScript("window.alert = function(msg){};");
((JavascriptExecutor) driver).executeScript("window.confirm = function(msg){return true;};");

How FirefoxDriver opens Firefox Browser 
A beta features which makes Firefox Faster 
Enable Firebug in Session started by FirefoxDriver 
How FirefoxDriver Executes the Selenium Commands 

How FirefoxDriver opens the firefox browser?

When the following line is executed

FirefoxDriver driver = new FirefoxDriver();

1)Grab the port
    a)By default firefox attempts to grab the port 7055
    b)7055-1 = 7054, This is called as locking port, which we use as a mutex to make sure only one instance of firefox is started at the time
    c)Sit in a loop waiting the the locking port to become free
    d)Exit loop when we can establish a connection to the server socket(A server socket waits for requests to come in over the network. It performs some operation based on that request, and then possibly returns a result to the requester.) to the locking port. This driver now has the mutex

2)Find the next free port up from the locking port
    Identify the next free port above the locked one by attempting to bind to each of them in turn. Release the newly found port. For the first driver, this will be 7055.

Until this point the FirefoxDriver has created a socket and FirefoxDriver is listening at the port 7055 for the incoming commands that needs to be executed
But we have not yet launched the browser

3)Locate the Firefox profile to use. This is normally an anonymous one

4)Copy the existing profile to a temporary directory,

5)Delete the current "extensions.cache" to force Firefox to look for newly installed extensions on start up.

6)Update "user.js" with the preferences required to make WebDriver work as expected.
(This is where the Capabilities are set for the browser, Eg EnableJavascript etc)

7)Set the "webdriver_firefox_port" value to the one that we found in the step 2.

Until this point the FirefoxDriver has created a socket and FirefoxDriver is listening at the port 7055 for the incoming commands that needs to be executed
We have selected the profile(default) or the one given from code and the Desired Capabilities are set

8)Start Firefox with the "-silent" flag and telling it to use the freshly minted directory as the profile.
Finally, we launch the Firefox Browser which we can see..!!

9)Wait until that Firefox instance has finished and the process has died.

10)Release the locking port. The mutex has now been freed.

Handle Race Condition in Alerts with Webdriver 
A beta features which makes Firefox Faster 
Enable Firebug in Session started by FirefoxDriver  
How FirefoxDriver Executes the Selenium Commands 

A Beta feature which makes Firefox Webdriver considerable fast


There is beta feature to make firefox not wait for the full page to load after calling .get or .click. This may cause immediate find's to break, so please be sure to use an implicit or explicit wait too. This is only available for Firefox and not other browsers.

   FirefoxProfile fp = new FirefoxProfile();
   fp.setPreference("webdriver.load.strategy", "unstable");
   WebDriver driver = new FirefoxDriver(fp);

Handle Race Condition in Alerts with Webdriver 
How FirefoxDriver opens Firefox Browser 
Enable Firebug in Session started by FirefoxDriver
How FirefoxDriver Executes the Selenium Commands

How to Enable Firebug in the Mozilla session started by Webdriver

Download the firebug xpi file from mozilla and start the profile as follows:

   File file = new File("firebug-1.8.1.xpi");
   FirefoxProfile firefoxProfile = new FirefoxProfile();
   firefoxProfile.addExtension(file);
   firefoxProfile.setPreference("extensions.firebug.currentVersion", "1.8.1"); // Avoid startup screen

   WebDriver driver = new FirefoxDriver(firefoxProfile);

Handle Race Condition in Alerts with Webdriver 
How FirefoxDriver opens Firefox Browser 
A beta features which makes Firefox Faster 
How FirefoxDriver Executes the Selenium Commands 

How Firefox executes the Selenium commands

//How webdriver sends commands to Firefox
--------------------------------
1)Webdriver creates a map/dictionary(based on programming language) with

context : String, opaque key by client language(Redundant)
commandName : The name of the command to execute
parameters : A list of parameters, The typoe depends on the command, This can be empty
elementId : String and an opaquekey that represents the identifier for a particular element

2)Serialize the map using JSON

3)Connect to the socket opened by the Firefox

4)Send the JSON across wire to Firefox

5)It will be Block until the response is sent

//Firefox executes the command
------------------------------

6)Once the command has reached the Firefox, it is deserialized from JSON to Javascript Object

7)The command name is interpreted

8)Some commands don't pay attention to context, for some that do, context is interpreted as window or frame.

9)In order to execute the command, it is looked up in FirefoxDriver prototype.

     eg :
     String url = "http://google.com"
     driver.get(url);

is same as

FirefoxDriver.prototype.get = function(respond, url)

Each function takes at least one parameter: the object that represents the response

FirefoxDriver.prototype.getCurrentUrl = function(respond) {
respond.context = this.context;
respond.response = Utils.getBrowser(this.context).contentWindow.location;
respond.send();
}

10) Calling the "send" method causes the response to be sent via the socket connection back to the client

//Webdiver reads the response
------------------------------

11)The response is another map serialzed in JSON,

methodName : String, Should match "commandName" from the original command sent
context : same as what was sent
isError : Indicated some error has occured(In java this will cause the exception)
responseText A string who's meaning differs depending on the command.

12)If "isError" is true, this will be a description of the error that actually occurred.

Handle Race Condition in Alerts with Webdriver 
A beta features wihich makes Firefox Faster
How FirefoxDriver opens Firefox Browser
Enable Firebug in Session started by FirefoxDriver 
How FirefoxDriver Executes the Selenium Commands

Sunday, January 25, 2015

How to move Slider using Selenium Webdriver


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

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;


public class slider {

    public static void main(String[] args) {
       
       
        WebDriver driver = new FirefoxDriver();
        driver.get("http://jqueryui.com/demos/slider/");
        //Identify WebElement
        driver.manage().window().maximize();
        driver.switchTo().frame(0);
       
        WebElement slider = driver.findElement(By.xpath("//span[@class='ui-slider-handle ui-state-default ui-corner-all']"));
       
        //Using Action Class
        Actions move = new Actions(driver);
        Action action = move.dragAndDropBy(slider, 100, 0).build();
        action.perform();

        //driver.quit();

    }

}

Saturday, January 10, 2015

File Handling in Perl


Keyboard is considered as a file in most OS
<STDIN> is the file handle used to read from the keyboard
when we use STDIN in <>(angular) brackets it will return the file pointer or file handler using which we can read the contents from the Keyboard

A very simple example

    eg : print "Enter your name";
         $name = <STDIN>; # Read from the keyboard
         print "Good Morning, $name..!! \n";
       
         When you execute the program you will notice that it will print two new lines
         //$name will also contain the new line character
       
Chop function
---------------
This will remove the last character of whatever is given to it.

So we can rewrite the above program as
    print "Enter your name";
    chop($name = <STDIN>);
    print "Good Morning, $name..!! \n";

    This time the program will only print one new line char which is given in the program
    But remenber chopping sometimes might not be good, becuse it blindly removes the last char irrespective of what it is
   
Chomp Function
----------------
The chomp functions similar to the chop, witha difference that it chops of the last char only if it is a new line char
       
    print "Enter your name";
    chomp($name = <STDIN>);
    print "Good Morning, $name..!! \n";
   
Opening a File in Perl
-----------------------

The open command opens the file and return the file handle

For standard input we had a predefined file handle <STDIN>

    eg : $file = "/home/bin/report.txt";
         open XYZ, $file;
         while(<XYZ>) {
         print "Line number $. is $_";
         }
       
         Difference between XYZ and <XYZ> is , XYZ represents the file and <XYZ> represents the contents of the file
       
         $. is the line number
         $_ is the present line which is being read
       
         Sometimes file name may be wrong, or file may not exist, to handle that we use the following construct
       
         $file = "/home/bin/report.txt";
         open XYZ, $file or die "Error in open: $!"
         while(<XYZ>) {
         print "Line number $. is $_";
         }
       
         $! returns the error code or message
       
Reading from the file in Perl
-------------------------------

The <> is the line input operator, all the data read goes into $_

Writing into a file in Perl
----------------------------

    Eg : $out = "/home/bin/out.txt";
         open XYZ, ">$out" or die "Error in Write : $!" ;
         for $i (1..20) {
         print XYZ "$i :: Hello the time is scalar(localtime) \n";
         }
       
         Here ">$out" open the file given in the path
         print XYZ, will write the output to the file and not on the screen
         scalar(localtime) is the function in perl which returns the system time.
       
Appending the file
-------------------

        Eg : $out = "/home/bin/out.txt";
         open XYZ, ">>$out" or die "Error in Write : $!" ;
         for $i (1..20) {
         print XYZ "$i :: Hello the time is scalar(localtime) \n";
         }
       
        Here ">>$out" will open the file for appending
       
Print the file in Perl
------------------------
Print the contents of Perl is very easy

    eg : $out = "/home/bin/out.txt";
         open IN $input or die "Error in opening : $!";
         while(<IN>){
         print;         //By defaults print $_
         }
         close IN;
       
Command line args in Perl
--------------------------

Perl uses special array called @ARGV

List of arguments passed in the command line along with the scipt name will be stored in @ARGV

    eg : If ou invoke perl as
        perl test.pl red blue green
       
        then @ARGV wil be red blue green
       
        printing the command line arguments
       
        foreach(@ARGV) {
        print "$_";
        }
       
Difference between @ARGV and <ARGV>
--------------------------------------

@ARGV will contain the text after the scrpt nam efrom thr command line
<ARGV> will assume that each element after the script name is a name of the file
If no file name is given and <ARGV is used then by default it starts reading from the default input it keyboard

Consider an example
    This program will print the contents of the file you are passing
   
    eg : $lineno = 1;
         while(<>) {
            print $lineno++;
            print ":$_";
         }
       
         perl list_lines.pl file1.txt //contents of the file file1.txt will be printed
         perl list_lines.pl a.txt b.txt c.txt //contents of all the three files
       

       
       

       
   
       
       

Thursday, January 8, 2015

How to create logs in XML format using Log4j

1)Create a project in Eclipse

2)Create a file - log4j.properties and paste the following content in it

# Define the root logger with file appender
log4j.rootLogger = DEBUG, XML

# Define the file appender
log4j.appender.XML=org.apache.log4j.FileAppender
log4j.appender.XML.File=application.xml

# Define the xml layout for file appender
log4j.appender.XML.layout=org.apache.log4j.xml.XMLLayout
log4j.appender.XML.layout.LocationInfo=true
log4j.appender.XML.Threshold=DEBUG


3)Create a sample class to log

(Make sure log4j jar file is added in the build path)

import org.apache.log4j.Logger;

public class Log4j_and_Xml
{
    static Logger log = Logger.getLogger(Log4j_and_Xml.class);

    public static void main(String[] args)
    {
        log.debug("This is debug message");
        log.info("This is info message");
        log.error("This is error message");
        log.fatal("This is  fatal message");
    }
}

Refresh the project to find the application.xml file
That's it, run the program and all logs will be created in XML format

Saturday, January 3, 2015

How to create logs in HTML formats using log4j

1)Create a project in Eclipse
2)Create a file - log4j.properties and paste the following content in it

# Define the root logger with file appender
log4j.rootLogger = DEBUG, HTML

# Define the file appender
log4j.appender.HTML=org.apache.log4j.FileAppender
log4j.appender.HTML.File=application.html

# Define the html layout for file appender
log4j.appender.HTML.layout=org.apache.log4j.HTMLLayout
log4j.appender.HTML.layout.Title=Application logs
log4j.appender.HTML.layout.LocationInfo=true
log4j.appender.HTML.Threshold=DEBUG

3)Create a sample class to log
(Make sure log4j jar file is added in the build path)

import org.apache.log4j.Logger;

public class log4j_and_html
{
    static Logger log = Logger.getLogger(log4j_and_html.class);

    public static void main(String[] args)
    {

        log.debug("Sample debug message");
        log.info("Sample info message");
        log.error("Sample error message");
        log.fatal("Sample fatal message");
    }
}

That's it, run the program and all logs will be created in HTML format


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);