Monday, June 24, 2013

QTP(HP UFT) Synchronization statements and methods


QTP(HP UFT) Synchronization statements and methods
Synchronization methods in QTP :
  1.      Wait statement
  2.      Exist Property
  3.      Do While ( Conditional statement )
  4.      Sync ( this method is applicable only for web based appliations)
  5.      Synchronization : (An option in QTP)
1. Wait Statement: As word says it will wait for the specified amount of time before proceed to next line of statement to execute. We can specify the time in both seconds and milliseconds. It’s necessary to define time in the wait statement even it is zero else it will give you an error.

Syntax : Wait 5 / Wait (5)

·         Invalid Example : wait, wait () both will give errors.
·         Valid Examples : while  wait(0), wait 0, wait 0, 10000 are valid statements.

Wait statement with milliseconds

·         Valid : wait 0,10000 is a valid statement.
·         Invalid : wait (0, 10000) will give an error

Disadvantage of wait statement :

The disadvantage of wait statements is that it can’t be applied on a condition. If this statement is encountered by the compiler then it will wait for the specified amount of time. If specified time amount is too long then optimization will be the problem.

2. Exist Property: A property which can used while dealing with dynamic objects which takes time to display on the web pages. As the name suggests this property checks if the object exist on AUT before doing operations on the object. This property can be applied to almost all the objects. It is used as follows:

Syntax : Exist(10)

Example : objExist=Browser("").Page("").Frame("").webedit("Login").exist(09)

The above exist statement will check if the "Login" webbutton object exists on the WebPage or not. If it exist then it return True to “objExist”: and if not then it will return False to “objExist”. In real time we generally checks if some objects exist or not before doing some operation on it.

Example :
 
If Browser("Gmail").Page("Gmail").WebButton(“Login”).Exist(10) then     Browser("Gmail").Page("Gmail").WebButton(“Login”).Click   end if 

Difference between wait and Exist Statement:
Wait Statement
Exist method
Execution will wait specifically for the amount specified in Wait statement. If wait(10) is define then the QTP will wait for 10 seconds. No matter what happens. So if we have a script which runs 100 times then naturally it is going to increase the run time significantly.
Exist: Execution will move to next statement as soon as Exist return a True. So if Exist(10) is specified and the condition become true on the very first second then QTP will move to next statement. Thus we have directly saved the 9 second.
Wait is a statement
Exist is a property
Wait pause the execution for certain amount of time
Exist checks if a specified objects exists or not for the specified time
Syntax : Wait 5 / Wait (5)
Example :
objExist =B("").P("").WebEdit("").Exist - Good 
objExist = B("").P("").WebEdit("").Exist(10) - Good
Invalid Example : wait, wait () both will give errors.
Valid Examples : while  wait(0), wait 0, wait 0, 10000 are valid statements.
Exist can't be used with the empty braces.
Exist statement with Empty braces will wait for the object synchronization time i.e. if the time is not specified in the exist statement then it will take the time from object synchronization timeout.
Wait statement with milliseconds

Valid : wait 0,10000 is a valid statement.
Invalid : wait (0, 10000) will give an error
Exist can't be used with the empty braces. It will give u error. However we can use it with the "0" in Exist
objExist =B("").P("").WebEdit("").Exist() - Error
objExist =B("").P("").WebEdit("").Exist(0) – Good
objExist =B("").P("").WebEdit("").Exist  - will wait for Object synchronization time by default 20 secs
3. Do While: For Dynamic object in AUT “Do while loop” is a best option to synchronize. Objects in AUT are visible based upon state of some other objects. For example in an application we have submit forms/submit details pages/upload attachments etc; in these cases the next page generally takes times to load, time load varies depends upon the size, number, connection speed & server response time. So we can implement a simple “Do while loop” it will instruct to QTP to wait till the next page is visible. We can specify the timeout period in the loop to,  just in case something goes wrong.

 Example:

Dim propWait
propWait =0

Browser("").Page("").Frame("").Link("").Click
Do
If Browser("").Page("").Frame("").WebTable(""").Exist(5) Then
         If trim(Browser("").Page("").Frame("").WebTable("").getcelldata(1,1))= Then 
                    Exit Do
         end if    
end if        
propWait = propWait +1   ' propWait  is used to track no of attempts made to identify object.
If propWait =5  Then
      Reporter.ReportEvent micFail,"", ""
      ExitActionIteration
elseif propWait =2 then
      Browser("").Page("").Frame("").Link("").Click  ' perform click operation on link again.
end If
Loop until Counter    > 5  
' forcibly exit in case object webtable is not found after 5 attempts

The above loop wait for the webtable to upload after clicking on a particular link. The loop keeps on checking some specific value ( Header of the webtable) till specified amount of time. If the webtable has not appeared the script click on the link again to do submit the upload webtable request again. If the webtable is not uploaded after 5 attempts then it will report the fail and skips to the next action iteration.

4 Sync Method: We can use the Browser and Page sync methods to synchronize the Browser and Page navigation

The following sync statements will wait for the browser to complete its navigation i.e. till the browser status bar displays "Done"
Browser("").sync

The following sync statements will wait for the page to download i.e. displayed. Whenever we navigate to a page the page gets download, the page sync wait till the page is displayed
Browser("").Page("").sync

5 WaitProperty/ inserting synchronization from QTP tool

Option Explicit
Dim orderNo, App_path
App_path = Environment( "ProductDir" ) & "\samples\flight\app\"   ' ProductDir is In-built environment variable
SystemUtil.Run "flight4a.exe", "", App_path ,"open"

If Dialog("Login").Exist( 2000 ) Then 'A way of synchronization
    Dialog("Login").WinEdit("Agent Name:").Set "tester"
    Dialog("Login").WinEdit("Password:").Set "Mercury"
    Dialog("Login").WinButton("OK").Click
    wait 1
Else
    Reporter.ReportEvent micFail, "Synchronization time-out", "Login dialog is not dispalyed"
    ExitTest( "your test name" )  ' it is the name of your QTP Test
End If
If Not Window("Flight Reservation").Exist( 2000 ) Then
    Reporter.ReportEvent micFail, "Synchronization time-out", "Flight Reservation window is not dispalyed"
    ExitTest( "write u r test name here" )  ' it is the name of your QTP Test
End If

    Window("Flight Reservation").WinButton("Button").Click
    Window("Flight Reservation").ActiveX("MaskEdBox").Type "010112"
    Window("Flight Reservation").WinComboBox("Fly From:").Select "London"
    Window("Flight Reservation").WinComboBox("Fly To:").Select "Los Angeles"
    Window("Flight Reservation").WinButton("FLIGHT").Click
    Window("Flight Reservation").Dialog("Flights Table").WinButton("OK").Click
    Window("Flight Reservation").WinEdit("Name:").Set "Tester"
    Window("Flight Reservation").WinEdit("Tickets:").SetSelection 0,1
    Window("Flight Reservation").WinEdit("Tickets:").Set "2"
    Window("Flight Reservation").WinRadioButton("First").Set
    Window("Flight Reservation").WinButton("Insert Order").Click
    Window("Flight Reservation").ActiveX("Threed Panel Control").WaitProperty "text", "Insert Done...", 2000
    orderNo = Window("Flight Reservation").WinEdit("Order No:").GetROProperty("text")
    MsgBox orderNo, vbInformation, "Order Number"

Monday, June 17, 2013

QTP Descriptive Programming (DP) : Description Object - Creating Object with Descriptions


Description Object - Creating Object with Descriptions

'Description is an object which contains collection of properties, which identify any UI object such as a browser, a page, a dialog, a list, a button etc.

Set dialog_login = Description.create
dialog_login("text").value ="Login" ' Assigning "Login" value to "text" property to identify an object with this value.

'Creating a description object with two properties to uniquely identify the edit object in AUT
Set edit_agentname = Description.Create
edit_agentname("micClass").value = "WinEdit"
edit_agentname("attached text").value = "Agent Name:"

'Creating a description object with two properties to uniquely identify the edit object in AUT
Set edit_password = Description.Create 'Creating an object for WinEdit i.e. for text box
edit_password("micClass").value = "WinEdit"
edit_password("attached text").value = "Password:"

'Creating a description object with two properties to uniquely identify the button object in AUT
Set button_ok = Description.Create
button_ok("micClass").value = "WinButton"
button_ok("text").value ="OK"

Dialog(dialog_login).Activate
Dialog(dialog_login).WinEdit(edit_agentname).Set "Ravi"
Dialog(dialog_login).WinEdit(edit_password).Set "mercury"
Dialog(dialog_login).WinButton(button_ok).Click

Sunday, June 16, 2013

SOAP UI Groovy Scripts

------------------------------------------------------------------------
//Read input values from window prompt and setting read at testsuite level
------------------------------------------------------------------------
import com.eviware.soapui.support.*
def alert = com.eviware.soapui.support.UISupport
def userName = alert.prompt("Username","Webservices-UserName")
def password = alert.prompt("Password","Webservices-Password")
testSuite.setPropertyValue( "userName", userName)
testSuite.setPropertyValue( "password", password)
---------------------------------------------------------------------------------
------------------------------------------------------------------------
//Read input values from window prompt and setting read at project level
------------------------------------------------------------------------
import com.eviware.soapui.support.*
def alert = com.eviware.soapui.support.UISupport
def userName = alert.prompt("Username","Webservices-UserName")
def password = alert.promptPassword("Password","Webservices-Password").toString()
project.setPropertyValue( "userName", userName)
project.setPropertyValue( "password", password)
-------------------------------------------------------------------------------------
//SOAP UI Groovy script to create and write data into excel
------------------------------------------------------------------------
import jxl.*
import jxl.write.*
WritableWorkbook WritableExcel = Workbook.createWorkbook(new File("D:\\yt.xls"))
WritableSheet sheet = WritableExcel.createSheet("H",0)
log.info(sheet)
Label label = new Label(0, 2, "Text input in Excel");
sheet.addCell(label);
WritableExcel.write()
WritableExcel.close()
--------------------------------------------------------------------------------------
//SOAP UI GROOVY SCRIPT TO WRITE A FOLDER AND THEN WRITING TXT OR EXCEL FILE INTO IT
------------------------------------------------------------------------

createFolder = new File("D:/SOAPUI/sam2922")  
createFolder.mkdir()
file = new File("D:/SOAPUI/sam2922.xls")
file.createNewFile()
Workbook workbook = Workbook.getWorkbook(new File("D:/SOAPUI/sam2922/ash9.xls"))
------------------------------------------------------------------------
//SOAP UI GROOVY SCRIPT FOR SETTING A JDBC CONNECTION AND THEN RETRIEVING VALUE FROM TABLE AND THEN PASSING IT TO NEXT STEP
------------------------------------------------------------------------
import groovy.sql.Sql
groovyUtils = new com.eviware.soapui.support.GroovyUtils( context )
sql = Sql.newInstance("jdbc:oracle:thin:int_db/Oracle11g@XX.YYY.ZZZ.QQ:1111:DDDD", "oracle.jdbc.driver.OracleDriver")
row = sql.firstRow("SELECT * FROM ORDERS WHERE ORDER_NUM= 'wegfdsfdsfGSFT'")
FIRSTNAME= row.FIRSTNAME
context["FIRSTNAME"] = row.FIRSTNAME
def string1 = FIRSTNAME;
context.setProperty("FIRSTNAME",string1)
log.info context.getProperty("FIRSTNAME")
---------------------------------------------------------------------------------
//SOAP UI GROOVY SCRIPT FOR ASSERTING WHETHER A PARTICULAR NODE VALUE IS STRING OR NOT
------------------------------------------------------------------------
groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)
holder = groovyUtils.getXmlHolder("GetManuscriptFileListView - Request 1-Response")
out = holder.getNodeValue("//FileId")
assert out.class == String
----------------------------------------------------
//SOAP UI GROOVY SCRIPT TO GET THE NAME OF A PROJECT
a = testRunner.testCase.testSuite.project.name
---------------------------------------------------------------------------------
//SOAP UI GROOVY SCRIPT TO GET THE RESPONSE FROM A TEST STEP
---------------------------------------------------------------------------------
b = testRunner.testCase.getTestStepByName("GetManuscriptFileListView - Request 1").getProperty("Response").getValue()
---------------------------------------------------------------------------------
//SOAP UI GROOVY SCRIPT TO GET THE RESPONSE OF A TEST STEP    
---------------------------------------------------------------------------------
a = testRunner.testCase.getTestStepByName("GetManuscriptFileListView - Request 1")
responseData = a.getProperty( "Response" )
log.info(responseData.value)
---------------------------------------------------------------------------------
//SOAP UI  GROOVY SCRIPT TO WRITE A RESPONSE TO TEXT FILE
---------------------------------------------------------------------------------
createFolder = new File("D:/SOAPUI/SAM222")  
createFolder.mkdir()
file = new File("D:/SOAPUI/SAM222/ash16.txt")
file.createNewFile()
a = testRunner.testCase.getTestStepByName("GetManuscriptFileListView - Request 1")
responsedata = a.getProperty( "Response" )
file.write(responsedata.value)
---------------------------------------------------------------------------------
//SOAP UI GROOVY SCRIPT TO GET HOLD OF TESTSUITE, TEST CASE, TEST STEP
---------------------------------------------------------------------------------
testSuite = testRunner.testCase.testSuite.project.testSuites["ManuscriptServiceTestSuite"]
testCase = testSuite.getTestCaseAt(0)
testStep1 = testCase.getTestStepCount()
---------------------------------------------------------------------------------
//SOAP UI GROOVY TEST SCRIPT TO WRITE TODAY'S DATE TO A TEXT FILE AND ALSO TO PROPERTY STEP
---------------------------------------------------------------------------------
log.info("In the WeatherTestSuite Setup Script")
sdf = new java.text.SimpleDateFormat("yyyy-MM-dd")
todayStr = sdf.format(new Date())
props = new java.util.Properties ()
file = new File("D:/SOAPUI/SAM222.txt")
if(!file.exists())
{
file.createNewFile()
fis = new FileInputStream (file )
props.setProperty ( "today" , todayStr)
props.setProperty ( "zipCode" , "20904")
fos = new java.io.FileOutputStream ( file )
props.store(fos, "Writing the zipcode and today's date")
}
---------------------------------------------------------------------------------
//SOAP UI GROOVY SCRIPT FOR WRITING VALUES TO PROPERTY STEP
---------------------------------------------------------------------------------
a = testRunner.testCase.getTestStepByName("Properties")
a.setPropertyValue("SystemId", "80")
a.setPropertyValue("Section", "90")
---------------------------------------------------------------------------------
//SOAP UI GROOVY SCRIPT FOR ASSERTING WHETHER A PARTICULAR NODE VALUE IS STRING OR NOT
---------------------------------------------------------------------------------
groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)
holder = groovyUtils.getXmlHolder("GetManuscriptFileListView - Request 1-Response")
out = holder.getNodeValue("//FileId")
assert out.class == String
---------------------------------------------------------------------------------
//SOAP UI  Groovy Script: Generate random string from given character set
---------------------------------------------------------------------------------
def generator = { String alphabet, int n ->
  new Random().with {
    (1..n).collect { alphabet[ nextInt( alphabet.length() ) ] }.join()
  }
}
generator( (('A'..'Z')+('0'..'9')).join(), 9 )
---------------------------------------------------------------------------------i
//SOAP UI  Groovy Script: Generate random numbers
---------------------------------------------------------------------------------
nt a = 9
nr = "CONT"
for(i = 0; i < 5; i++)
{
random = new Random()
randomInteger= random.nextInt(a)
nr = nr + randomInteger
}
log.info nr
---------------------------------------------------------------------------------i
//SOAP UI  Groovy Script: Generate random number and set value at test case level
---------------------------------------------------------------------------------
a = testRunner.testCase.getTestStepByName("Properties")
nr = "CONT"
b = nr+String.valueOf((int)Math.random()*100000)
a.setPropertyValue("TransID", b);
---------------------------------------------------------------------------------
//SOAP UI GROOVY SCRIPT TO CREATE A EXCEL WORK BOOK TIME STAMP
---------------------------------------------------------------------------------
def  timestamp = new Date().format("yyyyMMddhhmm")
log.info (timestamp)
file name    ("d:\\output-"+timestamp+".xls"))
---------------------------------------------------------------------------------
//SOAP UI GROOVY SCRIPT LOOP TEST CASE FOR MULTIPLE TIMES
for( c in 0..5 )
testRunner.runTestStepByName( “My Request” )
---------------------------------------------------------------------------------

SOAP UI : SetUp HTTP Basic Authentication for soapUI Test Suties


SetUp HTTP Basic Authentication for soapUI Test Suties

import com.eviware.soapui.impl.wsdl.teststeps.*
for( testCase in testSuite.getTestCaseList() )
{
log.info("Setting HTTP basic auth for all WSDL test requests in test case ["+ testCase.getLabel()+"]")
for( testStep in testCase.getTestStepList() )
{
if( testStep instanceof WsdlTestRequestStep )
{
//Create UNAME variable in tesSuite testProperties and assign Value to it.
testStep.getTestRequest() .setUsername(testSuite .getPropertyValue("UNAME"))
//Create PASSWORD variable in tesSuite testProperties and assign Value to it.
testStep.getTestRequest() .setPassword(testSuite .getPropertyValue("PASSWORD"))
}
}
}

Saturday, June 15, 2013

QTP:Methods GetTOproperties, GetTOproperty & GetROproperty

QTP : Methods GetTOproperties, GetTOproperty & GetROproperty

SetTOproperty : method is used to set the value of a particular property of an object in the object repository.

Note : Whatever value we set during the script execution is not retained after the execution is complete. The values in the OR automatically gets back to what it was at the beginning of the execution.

'#############################################
'### Set TO Property
'#############################################

Systemutil.Run "iexplore.exe", "http://www.mail.yahoo.com"
Browser("Yahoo! India").Page("Yahoo! Mail: The best").WebEdit("login").Set "tester"
'Changing the login object name property value from "login" to "passwd"
Browser("Yahoo! India").Page("Yahoo! Mail: The best").WebEdit("login").SetTOProperty "name","passwd"
'Below statement  enters value in password  field
Browser("Yahoo! India").Page("Yahoo! Mail: The best").WebEdit("login").Set "xyz@123"
Browser("Yahoo! India").Page("Yahoo! Mail: The best").WebButton("Sign In").Click

'#############################################
'### Set TO Property & Get TO property ###
'#############################################

Systemutil.Run "iexplore.exe", "http://www.mail.yahoo.com"
Browser("Yahoo! India").Page("Yahoo! Mail: The best").WebEdit("login").Set "tester"
oldName = Browser("Yahoo! India").Page("Yahoo! Mail: The best").WebEdit("login").GetTOProperty("name")
MsgBox oldName
'Changing the login object name property value from "login" to "passwd"
Browser("Yahoo! India").Page("Yahoo! Mail: The best").WebEdit("login").SetTOProperty "name","passwd"
'Below statement  enters value in password  field
Browser("Yahoo! India").Page("Yahoo! Mail: The best").WebEdit("login").Set "xyz@123"
newName = Browser("Yahoo! India").Page("Yahoo! Mail: The best").WebEdit("login").GetTOProperty("name")
MsgBox newName
Browser("Yahoo! India").Page("Yahoo! Mail: The best").WebButton("Sign In").Click

'##############
'### Result:###
'##############
' Old Name ->login
' New Name ->passwd
'### End of Script ###

GetROProperty: This method is used to get the runtime value of  a property in an application object.

'#######################
'### Get RO Property ### 
'#######################
oWebEdit=Browser("Yahoo! India").Page("Yahoo! India").WebEdit("p") 'have some text entered in the username field
msgbox oWebEdit

'###############
'### Result: ###
'###############
'### text from username field will be displayed
'### End of Script ###

GetTOproperties: method is used to read the properties and their corresponding values from the test objects(Test Objects > Objects which are stored in object repository).
The following example explains the usage of GetTOproperties method:

'################################'###
'##### Get TO Properties Script
'################################
Systemutil.Run "iexplore.exe", "http://www.yahoo.com"
Set oWebEdit=Browser("Yahoo! India").Page("Yahoo! India").WebEdit("p") 'Create webedit object
Set TOProperties=oWebEdit.GetTOProperties 'Get TO Properties
For i = 0 to TOProperties.count - 1
    sName=TOProperties(i).Name
    sValue=TOProperties(i).Value
    print sName & " -> " & sValue
Next

'##############
'### Result:###
'##############
name -> p
micclass -> WebEdit
html tag -> INPUT
abs_x -> 416
'### End of Script ####

Note:To run above scripts add two objects to OR, yahoo mail username field object and sign in button.