Saturday, December 6, 2008

To Know the Type of File

Set obj=createobject("Scripting.filesystemobject")
Set of=obj.getfile("c:\1.xls")
s=of.type
msgbox s

To Display the Files in a Particular Folder

folderpath="E:\macromedia-8"
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder(folderpath)
Set fc = f.Files

For Each f1 in fc
s = s & f1.name &chr(10)
Next

Displaying numbers into Ascending Order By Using Arrays

''''''''''''''''Displaying numbers into Ascending Order By Using Arrays'''''''''''''''''''''''''''''''''''''''''
a=array(10,20,1,30,2,40,23,50,4)

For j=lbound(a) to ubound(a)
For i=lbound(a) to ubound(a)-1
If a(i)>a(i+1) Then
temp=a(i+1)
a(i+1)=a(i)
a(i)=temp
End If
Next
For i=lbound(a) to ubound(a)
x=x&chr(10)&a(i)
'y=a(i)&chr(10)
Next

msgbox(x)

Swaping two numbers without using 3rd variable

a=inputbox ("Enter the first value:")
b=inputbox( "Enter the second value:")
msgbox "a= "&a&" b= "&b
a=int(a)+int(b)
b=int(a)-int(b)
a=int(a)-int(b)
msgbox "After swap a= "&a&" b= "&b

Write a Mathematical Table in Notepad through the VB Script

'To open notepad and write a mathematical table in that throug QTP and save in C Drive and close

Set obj=createobject("Scripting.filesystemobject")
Set of=obj.createtextfile("c:\mat.txt")
'set of=obj.opentextfile("c:\mat.txt")
For i=1 to 10
x=5*i
of.writeline"5 * "&i&" = "&x
Next

Comparing Two Files

''''''''''''''''''''''''Compare both the text files and isolate the differences found in the file1 which are not present in file2''''''''''''''''''''''''''''''''
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' in a seperate ouput file.''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

dim found
set objfso = createobject("scripting.filesystemobject")
set objinputfile2 = objfso.opentextfile ("c:\text2.txt")
set objoutputfile = objfso.createtextfile("c:\output.txt")

do until objinputfile2.atendofstream
found = false
strnextline2 = objinputfile2.readline
set objinputfile1 = objfso.opentextfile ("c:\text1.txt")

do until objinputfile1.atendofstream
strnextline1 = objinputfile1.readline

if (strnextline2 = strnextline1) then
found = true
end if
loop

objinputfile1.close

if (found = false) then
objoutputfile.writeline strnextline2
end if
loop

objinputfile2.close
objoutputfile.close
set objinputfile1 = nothing
set objinputfile2 = nothing
set objoutputfile = nothing

Writing Log Files

Public function generate_result()

starttime=time()
msgbox(nam)
MyArray=split(nam, ":", -1)

For i=0 to ubound(MyArray)
filename=filename+MyArray(i)
Next

Set fso=Createobject("Scripting.FileSystemObject")
Set textfile=fso.createtextfile("c:/result.txt")

textfile.Writeline("Automated Smoke Test Results")
textfile.WriteLine("````````````````````````````")
textfile.WriteBlanklines(3)
textfile.WriteLine("Run on Host : " & Environment.Value("LocalHostName"))
textfile.WriteBlanklines(1)
textfile.WriteLine("Run on Operating System : " & Environment.Value("OS"))
textfile.WriteBlanklines(1)
textfile.WriteLine("Run on : "&now)
textfile.WriteBlanklines(1)
endtime=time()
textfile.WriteLine("Test Start Time : " &starttime)
textfile.WriteLine("Test End Time : " & endtime)
textfile.WriteLine("Test Execution Time : " & datediff("s", startime, endtime)& " Seconds")

End Function

generate_result()

VB Script Procedures

'There are two types of procedures

'1. Function Procedure
'2. Sub Procedure

'Function Procedure-A Function procedure is a series of VBScript statements enclosed by the Function
'and End Function statements. Function Procedure can able to return the value.

'Example:

Function demo_add(a,b)

demo_add=a+b

End Function

oVal=demo_add( 2,3)

msgbox oVal 'Returns 5

'In this example demo_add function returns a value to oVal.
'In Function procedures we can use function name to assign a value.

'Sub Procedure-A Sub procedure is a series of VBScript statements enclosed by the Sub
'and End Sub statements. Sub Procedure cannot return any value.

'Example:

Sub demo_sub(a,b, c)
c=a+b
End sub

demo_sub 2,3,x
msgbox x 'Returns 5

'This example will do the same as what function procedure is doing above.
'But in sub Procedure we need to use one more parameter to get values from the sub procedure.

Use of Split Function

''''To display the words in a sentence by spliting with dellimeter''''

str1="arunsingh is a good boy"
var=split(str1," ")
lenarray=ubound(var)
For i=0 to lenarray
str2=var(i)
msgbox str2
Next

Use of RandomNumber Method

set da1=datatable.AddSheet("demo")
set da2=datatable.AddSheet("result")

set pm1=da1.addparameter("name","123")
set pm2= da1.addparameter("age","18")

For i=1 to 10
da1.setcurrentrow(i)
pm1.value="emp"&i
pm2.value=RandomNumber (30,60)
Next

x=da1.getrowcount
set pmr=da2.addparameter("resname","")
set pmg=da2.addparameter("age","")
k=1
For j=1 to x
ag=pm2.valuebyrow(j)

If ag>50 Then
pmr.valuebyrow(k)=pm1.valuebyrow(j)
pmg.valuebyrow(k)=ag
k=k+1
End If

Next

Use of Excel Object Model

''We can do excel operations using excel object model. To find excel object model in your system follow these steps..

'*********** ********* ********* ********* *
'creating an excel application object
Set Excel=CreateObject( "Excel.Application")
'Adding a sheet in that application
Set ExcelSheet = CreateObject( "Excel.Sheet" )
' Make Excel visible through the Application object.
ExcelSheet.Application.Visible = True

'Adding value into sheet
For i=1 to 10
ExcelSheet.ActiveSheet.Cells( i,1).Value = "This is column A, row"&i
Next

' Save the sheet.
ExcelSheet.SaveAs "C:\TEST.xls"
' Close Excel with the Quit method on the Application object.
ExcelSheet.Applicat ion.Quit
' Release the object variable.
Set ExcelSheet = Nothing
'*********** ********* ********* ********* *
''Copy this script in .vbs file and double click on it or paste this script in QTP and execute it.
''After that go C:\ drive you will find an excel application in the name of TEST.xls..
''Try to understand this by referring excel object model.. Revert me for any concerns..

How to set the value for a property

Setting.Add "Tester Name", "Mark Train"

MsgBox Setting("Tester Name")

Use of SetTOProperty

'For example..in first build there is a OK button..and u
'reorded on OK button..

'but in modified build it changed to Yes..and this
'modificatio is only for single build...in this situation u
'need to change that button name OK to Yes

'window("XXXX").winbutton("OK").SetTOProperty "Text","Yes"

To search for something in Google

url="ww.google.com"
systemutil.Run"IEXPLORE",url 'It is to Open a Browser with any website address

Set gBrowser=Browser("name:=Google.*")
Set gPage=gBrowser.Page("title:=Google.*")
gPage.webedit("name:=q","type:=text","html tag:=INPUT").set "QTP"
gpage.webbutton("name:=Google Search","index:=0","type:=submit","html tag:=INPUT").click

To Check weather the text contains a particular word or not

var="raju want to marry"
If instr(1,var,"want") Then
msgbox "Exist"
else
msgbox "doesnot Exist"
End If

To check/Uncheck all the checkboxes present on a web page

Systemutil.Run"IExplore","www.yahoomail.com"
wait(10)

Dim obj_DescChk

Set obj_DescChk=Description.Create
obj_DescChk("html tag").value="INPUT"
obj_DescChk("type").value="checkbox"

'obj_DescChk.remove "html tag" '''''''''''''''''''Would delete the html tag property from the collections
'If obj_DescChk("html tag").value=empty then ''''''''To Know the property is exists or not in the collection
'obj_DescChk("html tag").value="INPUT" '''''''''''''''''If not then add it to the collection
'end if

Dim AllChkBoxes, SingleChkBox
Set AllChkBoxes=Browser("title:=Yahoo! Mail: The best web-based email!").Page("title:=Yahoo! Mail: The best web-based email!").ChildObjects(obj_DescChk)
msgbox AllChkBoxes.count
For i=0 to AllChkBoxes.count-1
AllChkBoxes(i).set "ON"
Next

To retrive data from datatable which is in 3rd row and 4th column

'in Action1 sheet change the names of A,B,C,D columns with A,B,C,D respectively.
'And type the values in D column

datatable.SetCurrentRow(3)
answer=datatable(4,2)'.Value(4,2) '4th column in 2nd Sheet
msgbox answer
'Run the program

'-------------------------------------
'To retrive value from 3rd row 4th column from external excel sheet

datatable.Importsheet "c:/1.xls",1,1
datatable.SetCurrentRow(3)
val=datatable.Value(4,1)'4th column 1st sheet
msgbox "The Value is "&val

How to paste a image in Word Document

Set objWord = CreateObject( "Word.Application")
objWord.Visible = True
Set objDoc = objWord.Documents. Add()
Set objSelection = objWord.Selection

Set objShape = objDoc.Shapes
objShape.AddPicture ("c:\image010.jpg")

To Know the No of Items in the Web Page

url="http://my.naukri.com/manager/createacc2.php?othersrcp=5421&wExp=N"
'url="www.gmail.com"
'url="www.yahoomail.com"

If Browser("index:=0").Exist(1) then' If Browser is already opened
a = Browser("index:=0").GetROProperty("hwnd")
Browser("hwnd:=" & a).Navigate(url)
Browser("hwnd:=" & a).Sync
wait(2)
Else' If Browser is not opened
SystemUtil.Run"IEXPLORE.exe"
a = Browser("index:=0").GetROProperty("hwnd")
Browser("hwnd:=" & a).Navigate(url)
Browser("hwnd:=" & a).Sync
wait(2)
End If

Set Editobj=Description.Create'For WebEdits
Editobj("html tag").value="INPUT"
Editobj("kind").value="singleline"

Set Butobj = Description.Create'For Buttons
Butobj("html tag").value = "INPUT"
Butobj("type").value="submit"

Set Listobj=Description.Create'For Web Lists
Listobj("html tag").value="SELECT"

Set Linkobj=Description.Create'For Link
Linkobj("html tag").value="A"

Set Checkboxobj=Description.Create'For Checkboxes
Checkboxobj("html tag").value="INPUT"
Checkboxobj("type").value="checkbox"

Set Radioobj=Description.Create'For Radio Buttons
Radioobj("html tag").value="INPUT"
Radioobj("html id").value="ctctype_i"


Set Edits = browser("hwnd:=" &a).Page("title:=.*").ChildObjects(Editobj)
Set Buttons = browser("hwnd:=" &a).Page("title:=.*").ChildObjects(Butobj)
Set Lists = browser("hwnd:=" &a).Page("title:=.*").ChildObjects(Listobj)
Set Links = browser("hwnd:=" &a).Page("title:=.*").ChildObjects(Linkobj)
Set Checks = browser("hwnd:=" &a).Page("title:=.*").ChildObjects(Checkboxobj)
Set Radios = browser("hwnd:=" &a).Page("title:=.*").ChildObjects(Radioobj)

msgbox "Total EditBoxes are : "&Edits.count
msgbox "Total Button are : "&Buttons.count
msgbox "Total Lists are : "&Lists.count
msgbox "Total Links are : "&Links.count
msgbox "Total checkBoxes are : "&Checks.count
msgbox "Total RadioButtons are : "&Radios.count

To Insert a Value in a Exce l Sheet

''''''''''''''''''''To Insert a Value in a Exce l Sheet'''''''''''''''''''''''''

Set xl=createobject("Excel.Application")
Set x=xl.workbooks.open("c:/arun.xls")
Set y=xl.activeworkbook.worksheets("sheet1")
xl.cells(1,1)="arun"

Wednesday, December 3, 2008

To get the only numbers from the flat file and store in a datatable

'bombay 100 hyderabad jkjk '
'djkhkk ksljk 88 asdk '
'dkjsajl kskj kjhsjk 88 '
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''To get the only numbers from the flat file and store in a datatable''''''''''''''''''''''''''''''''''''
set fso=createobject("scripting.filesystemobject")
set oText=fso.opentextfile("c:/demo.txt",1)
datatable.getsheet(1).addparameter"Numbers",""
row=1
While not oText.atendofline
text=oText.readline
n=split(text," ")
for i=lbound(n) to ubound(n)
If isnumeric(n(i)) then
datatable.setcurrentrow(row)
datatable(1,1)=n(i) '''''''''''''''datatable(ColumnNo,SheetNo)
row=row+1
end if
Next
wend

To Display the Files in a Particular Folder

'''''''''''''''''''To Display the Files in a Particular Folder'''''''''''''''''''''''''''''''''''

folderpath="E:\macromedia-8"
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder(folderpath)
Set fc = f.Files

For Each f1 in fc
s = s & f1.name &chr(10)
Next

To count the no of links and button in a web page

'''''''''''''''''''''''''Open A Google Page and Count the No Of Links and Buttons in that page'''''''''''''''''''''''''''''''''''
' '
' '
' '
' '
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
If Browser("index:=0").Exist(1) then' If Browser is already opened
a = Browser("index:=0").GetROProperty("hwnd")
Browser("hwnd:=" & a).Navigate("http://www.google.com")
Browser("hwnd:=" & a).Sync
wait(2)
Else' If Browser is not opened
SystemUtil.Run"IEXPLORE.exe"
a = Browser("index:=0").GetROProperty("hwnd")
Browser("hwnd:=" & a).Navigate("http://www.google.com")
Browser("hwnd:=" & a).Sync
wait(2)
End If

Set Butobj = Description.Create()'For Button
Butobj("html tag").value = "INPUT"'For Button
Butobj("type").value="submit"'For Button

Set Linkobj=Description.Create()'For Link
Linkobj("html tag").value="A"'For Link

Set Buttons = browser("hwnd:=" &a).Page("title:=.*").ChildObjects(Butobj)
Set Links = browser("hwnd:=" &a).Page("title:=.*").ChildObjects(Linkobj)

msgbox "Total Button are : "&Buttons.count
msgbox "Total Links are : "&Links.count

To copy contents of one file to another file

'To copy contents of one file to another file

Set fso=createobject("scripting.filesystemobject")
Set fname=fso.opentextfile("C:/mtable.txt",1)
Set fname1=fso.createtextfile("C:/duptable1.txt")
Do while not fname.atendofstream
n=fname.readline
fname1.writeline n
Loop

To Color the column in a excel sheet

'""""To Color the column in a excel sheet.""""""""""""""''''

Set xlApp=Createobject("Excel.Application")
set xlWorkBook=xlApp.workbooks.add
set xlWorkSheet=xlWorkbook.worksheets.add
xlWorkSheet.Range("A1:B10").interior.colorindex = 34 'Change the color of the cells
xlWorkSheet.Range("A1:A10").value="text" 'Will set values of all 10 rows to "text"
xlWorkSheet.Cells(1,1).value="Text" 'Will set the value of first row and first col

rowsCount=xlWorkSheet.Evaluate("COUNTA(A:A)") 'Will count the # of rows which have non blank value in the column A
colsCount=xlWorkSheet.Evaluate("COUNTA(1:1)") 'Will count the # of non blank columns in 1st row

xlWorkbook.SaveAs "C:\Test.xls"
xlWorkBook.Close
Set xlWorkSheet=Nothing
Set xlWorkBook=Nothing
set xlApp=Nothing

To know the no of list items in the web page

''''''''''''''''''''To know the no of list items in the web page'''''''''''''''''''''''''''''''''


url="http://corp.naukri.com/mynaukri/mn_newsmartsearch.php?xz=2_0_5&id="
Systemutil.Run "Iexplore.exe",url
set oDesc= Browser("name:=Mynaukri : naukri.com - India's No.1 Job Site")
itemcount=oDesc.WebList("name:=qe").GetROProperty("items count")
msgbox "Number of Items in Experience List= "& itemcount
itemcount=oDesc.WebList("name:=qm").GetROProperty("items count")
msgbox "Number of Items in Minimum Salary List= "&itemcount

Replace all text with a new text in a text file

Set oDesc=createobject("scripting.filesystemobject")
Set oFile=oDesc.opentextfile("c:/demo.txt",2,true)'''''1-Reading 2-Writing 3-Appending
oFile.write "Hello World"

Open Dialog box from Tool Menu of the MS Word Application

'This program will open a word pad and enter some text (impossibel) and checks the spelling and grammar in that text
'This program will open a word and opens a spelling and grammar dialog box for tools menu

Const wdDialogToolsSpellingAndGrammar = 828
Const wdDoNotSaveChanges = 0

Uncorrected = "impossibel"
Set Word = CreateObject("Word.Application")
Set Doc = Word.Documents.Add
Word.Selection.Text = Uncorrected
Word.Dialogs(wdDialogToolsSpellingAndGrammar).Show
If Len(Word.Selection.Text) <> 1 Then
Corrected = Word.Selection.Text
Else
Corrected = Uncorrected
End If
Doc.Close wdDoNotSaveChanges
Word.Quit

Multiple Screen shots at runtime

''''''''''''''''''''''''''''''''To create multiple screeen shots at runtime''''''''''''''''''''''''''''''''''''''

Systemutil.run"C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe"
Set Dlg= Dialog("text:=Login")
Set wnd=Window("text:=Flight Reservation")
Set oDlg=wnd.Dialog("text:=Open Order")

Dlg.WinEdit("attached text:=Agent Name:").set "rajaputra"
Dlg.WinEdit("attached text:=Password:").setsecure"mercury"
Dlg.WinButton("text:=OK").click

wait(7)
For i=1 to
wnd.Activate
wnd.WinButton("window id:=5").click
oDlg.WinCheckBox("text:=&Order No.").set "ON"
oDlg.WinEdit("window id:=1016").set "55"
oDlg.WinButton("text:=OK").click

if(oDlg.Dialog("text:=Flight Reservations").Exist) then
oDlg.Dialog("text:=Flight Reservations").CaptureBitmap"c:\snapshot"&i&".bmp"
oDlg.Dialog("text:=Flight Reservations").WinButton("text:=OK").click
oDlg.WinButton("text:=Cancel").click
end if
Next
wnd.Close

DP from Logging in - Open a Order and Closing the Flight Reservation Application

''''''''''''''' Discriptive Program for starting from Logging in - Opening a order and closing the Flight Reservation Application'''''''''''''
''''''''''''''Importing the Excel sheet into datatable and Exporting the Datatable into Excel file''''''''''''''''''''''''''''''''''''''''

systemutil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe"
Dialog("text:=Login").Activate
Dialog("text:=Login").WinEdit("attached text:=Agent Name:").set "rajaputra"
Dialog("text:=Login").WinEdit("attached text:=Password:").set "mercury"
Dialog("text:=Login").WinButton("text:=OK").click
wait(5)
Window("text:=Flight Reservation").Activate
datatable.Importsheet "c:/orders.xls",1,1' 1st sheet will be imported into the 1st sheet in runtime datatable
rowcount=datatable.GetRowCount
'msgbox rowcount
For i=1 to rowcount
Window("text:=Flight Reservation").WinButton("window id:=5").click
Dialog("text:=Open Order").Activate
Dialog("text:=Open Order").WinCheckBox("text:=&Order No.").set "ON"
datatable.SetCurrentRow(i)
n=datatable(1,1) '1st column 1st sheet
Dialog("text:=Open Order").WinEdit("window id:=1016").set n
Dialog("text:=Open Order").WinButton("text:=OK").click
If(window("text:=Flight Reservation").Dialog("text:=Open Order").Dialog("text:=Flight Reservations").exist)then
window("text:=Flight Reservation").Dialog("text:=Open Order").Dialog("text:=Flight Reservations").WinButton("text:=OK").click
window("text:=Flight Reservation").Dialog("text:=Open Order").WinButton("text:=Cancel").click
datatable(2,1)="Not Exist"'2nd column 1st sheet
Else
datatable(2,1)="Exist" '2nd column 1st sheet
end if
Next
DataTable.Exportsheet"C:\flight.xls",1'1st sheet of the runtime datatable will be exported at last sheet in flight.xls
Window("text:=Flight Reservation").Close

Importing Data from Flat File using Split function

'''''''''''''''''Importing Data From Flat File using split''''''''''''''''''''''''''''
''Source.txt file is having following data
''Arunsingh,40000,KiranKumar,35000,Chandra,50000
''Test Engineer,Developer,Project Leader

Set fso=createobject("scripting.filesystemobject")
Set z=fso.opentextfile("c:\source.txt",1)
l=1
While not z.atendofline
i=1
k=1
count=1
parname=inputbox("Enter Name of The Parameter "&l) '''''Enter the requiered parameter names
datatable.GetSheet(1).addparameter parname,""
n=z.readline
a=split(n,",")
For j=lbound(a) to ubound(a)

If isnumeric(a(j)) Then
If count=1 Then
datatable.GetSheet(1).addparameter "Salary",""
count=count+1
end if
datatable.SetCurrentRow(k)
m=l +1
datatable(m,1)=a(j)
k=k+1
else
datatable.SetCurrentRow(i)
datatable(l,1)=a(j)
i=i+1
end if
Next
l=m
l=l+1
Wend

Fixed VS Dynamic Arrays

'Using Fixed arrays

Dim x(2)

x(0)="how"
x(1)="are"
x(2)="you"

for i=lbound(x) to ubound (x)
msgbox x(i)
Next

'Here we cann't store more than 3 elements. Because this is a fixed length array..

'Using Dynamic Arrays

Dim x()

Redim preserve x(2)

x(0)="how"
x(1)="are"
x(2)="you"

Redim preserve x(3)
x(3)=123

'Here 'x' is a dynamic array and by redeclaring x it can able to store more values into it.

Displaying Numbers into Ascending Order

''''''''''''''''Displaying numbers into Ascending Order By Using Arrays'''''''''''''''''''''''''''''''''''''''''
a=array(10,20,1,30,2,40,23,50,4)

For j=lbound(a) to ubound(a)
For i=lbound(a) to ubound(a)-1
If a(i)>a(i+1) Then
temp=a(i+1)
a(i+1)=a(i)
a(i)=temp
End If
Next
Next

For i=lbound(a) to ubound(a)
x=x&chr(10)&a(i)
Next

msgbox(x)

Capture the Screen shot during runtime

''''''''''''''''''''''Capture the Screen Shot when Error Is Occured'''''''''''''''''''''''''''''''''''''
'''''''''''''''''''''''''''''''''''''Using Objects'''''''''''''''''''''''''''''''''''''''''''''''''
Systemutil.run"C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe"
Set Dlg= Dialog("text:=Login")
Set wnd=Window("text:=Flight Reservation")
Set oDlg=wnd.Dialog("text:=Open Order")

Dlg.WinEdit("attached text:=Agent Name:").set "rajaputra"
Dlg.WinEdit("attached text:=Password:").setsecure"mercury"
Dlg.WinButton("text:=OK").click

wait(7)

wnd.Activate
wnd.WinButton("window id:=5").click
oDlg.WinCheckBox("text:=&Order No.").set "ON"
oDlg.WinEdit("window id:=1016").set "55"
oDlg.WinButton("text:=OK").click

if(oDlg.Dialog("text:=Flight Reservations").Exist) then
oDlg.Dialog("text:=Flight Reservations").CaptureBitmap"c:\snapshot1.bmp"
oDlg.Dialog("text:=Flight Reservations").WinButton("text:=OK").click
oDlg.WinButton("text:=Cancel").click
end if

wnd.Close

Sunday, October 5, 2008

Export Datatable into Text File

Pre Requisite - abc.xls with one sheet with some values in first column

textfile="c:\demo.txt"
Set fso=createobject("scripting.filesystemobject")
Set f=fso.createtextfile(textfile,2)

datatable.Import("C:\abc.xls")
set dg=datatable.GetSheet(1)

x=dg.getparametercount
rc=dg.getrowcount

For i=1 to x
n=dg.getparameter(i).name ' Gives the First coulmn name
Set pmg=dg.getparameter(n)
f.writeline(n)
For j=1 to rc
f.writeline(pmg.valuebyrow(j))
next
Next

Use of Flat File

''''''''Pre requisite---Open A Note Pad and enter some order nos 1 by 1, and Save it as flat.txt in c:\\'''''''''''''''''''''''''

Set z=createobject("scripting.filesystemobject")
Set f=z.opentextfile("c:\flat.txt",1)
While f.atendofline<>true
n=f.readline
Window("Flight Reservation").WinMenu("Menu").Select "File;Open Order..."
Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON"
Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set n
Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click
Wend

Creating Constants

Constants-A constant is a meaningful name that takes the place of a number or string and never changes.
The difference between variable and constant is we can change the variable value in run time
but for constants its not possible.

Creating constants

const str="RAJAPUTRA"

here str is a constant and the value will never change.

We have public and Private constants. By default all are public. If you want specify the type then

Public const str="RAJAPUTRA"
or
Private const str="RAJAPUTRA"

Copying Files and Folders

Set fso=createobject("scripting.filesystemobject")
fso.copyfile"C:/SourceFileName.ext","c:/DestinationFile Name.ext" 'For copying a Files
fso.copyfolder "C:/SourceFolderName","C:/DestinationFolderName" ' For copying a Folders

Copy the Data from One Sheet to Another Sheet

'''Let assume we have a excel file called abc.xls in C drive.
'''In abc.xls we have one sheet with some values.
'''We need to copy first sheet values into second sheet

datatable.Import("c:\abc.xls")
Set src=datatable.GetSheet(1) 'Source Sheet
Set dsc=datatable.GetSheet(2) 'Destination Sheet

pc=src.getparametercount 'Get the Source sheet column count
rc=src.getrowcount 'Get the Source sheet row count

For i=1 to pc
n=src.getparameter(i).name ' Get the Source sheet column name
'msgbox n
Set pmg=src.getparameter(n)
Set pm=dsc.addparameter(n,"")

For j=1 to rc
pm.valuebyrow(j)=pmg.valuebyrow(j)
next
Next

By Value Vs By Reference

Types of arguments in procedures

1. ByVal
2. ByRef


ByVal:

Indicates that the argument is passed by value.

ByRef :
Indicates that the argument is passed by reference.

By default all arguments are 'ByRef'.

Syntax -

Function demo_add(a,b)

demo_add=a+b

End Function

Here a,b are the arguments. By default these are 'ByRef'.

In simple words ByRef Means the value which is assigned to the variable with in the function is permanent and we can use that value out side of that function also.

ByVal means the value which is assigned to the variable with in the function is temporary
and we can use that value only with in that function.

Example:

Function demo_parameters( byref x,byval y)
x=20
y=50
demo_parameters= x+y
End Function

a=10
b=20
msgbox demo_parameters( a,b)
msgbox a
msgbox b


In the above function x and y are the arguments, declared as byref and byval.
With in that function i assigned values to x and y.

Outside of the function i assigned values to two variables and passing those variables in to the function.
'a' is passing reference to x and b is passing value to y.

With in that function i am changing the value for x. This value is permanent for 'a'. Because 'a' is passed as 'ByRef'.

But the value of 'b' will not be changed because it is passed as 'ByVal'.

Sunday, July 20, 2008

To display the message box in two lines

msgbox "FIRSTLINE"&vbcrlf&"SECONDLINE"

To open a word doc,type something and save the doc and close

set WordObj = CreateObject("Word.Application")
WordObj.visible = true
Set WordDoc = WordObj.Documents.Add
WordDoc.Range.InsertBefore "Hi Good Morning!"
WordDoc.SaveAs "C:\Greetings.doc"
WordObj.quit
Set WordObj = nothing

Saturday, June 7, 2008

Defference between Import and ImportSheet

Import method will imports the specified Excel file to the run time datatable.
Ex: Datatable.Import ("C:\sample.xls")

ImportSheet method will imports a specified sheet of a specified file to a specified sheet in the datatable.
Ex: Datatable.ImportSheet "c:\sample.xls", SourceSheetName(or Number), DestinationSheetName(or Number)


If excel file has 7 sheets, if we use import method, then all the 7 Sheets are imported into the runtime datatabe?
The Answer is No. Only the first 2 sheets will be imported into the runtime datatable.
Not all the sheets.
why because, By default datatable will have 2 sheets (Global/Local)
If you add an action in the QTP then only, a new sheet will be added in to the datatable.

How to compare the list box items with another

Here i am giving the script to compare the list box items with another -
To run this script you have to add all the objects into the object repository
(Find the link in this blog "how to add objects into the object repository")

Window("Flight Reservation").activate
SeltItem = window("Flight Reservation").winComboBox("Fly From:").GerROProperty("text")
msgbox SelItem
'It displays the selected item in the list
ListItem = Window("Flight Reservation").WinComboBox("Fly To:").GetContent
msgbox ListItem
'It displays all the items in the list box
Itemcount = window("Flight Reservation").WinComboBox("Fly To:").GerItemsCount
msgbox Itemcount
'It displays no of items in the list box
For i=0 to Itemcount-1
a=window("Flight Reservation").wincombobox("Flt To:").GetItem(i)
If SelItem=a Then
msgbox "Items Are Matching"
else
msgbox "Items Are Not Matching"
End If
Next

Script for Orkut Login

url = "www.orkut.com"
Systemutil.Run "IExplore", url
'It will open a Browser with any website address
Browser("name:=orkut - login").WebEdit("name:=Email").set "rajaputra"
Browser("name:=orkut - login").WebEdit("name:= Passwd").setSecure "47525d8be4926ea2f6e96b9a3f7472b6ae38"
Browser("name:=orkut - login").WebButton("name:=Sigh in").Click
Browser("name:=orkut - login").Link("name:=Logout").Click
Browser("name:=orkut - login").Close

Friday, June 6, 2008

Import and Export Methods

Here i am giving the script for Importing data from data table and exporting the data table into Excel File.

SystemUtil.Run "C:\ProgramFiles\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe"

Dialog("text:= Login").Activate
Dialog("text: = Login").WinEdit("Attached text:=Agent Name").set "rajaputra"
Dialog("text: = Login").WinEdit("Attached text:=Password").set "mercury"
Dialog("text:=Login").WinButton("text:=OK").Click
Window("text:=Flight Reservation").Activate
datatable.importSheet "C:\example.xls",1,1
rowcount=datatable.GetRowCount
For i=1 to rowcount
Window("text:=Flight Reservation").WinButton("window id:=5").Click
Dialog("text:=Open Order").Activate
Dialog("text:=Open Order").WinCheckBox("text:=&Order No.").set "ON"
datatable.SetCurrentRow(i)
n=datatable(1,1)
Dialog("text:=Open Order").WinEdit("window id:=1016").set n
Dialog("text:=Open Order").WinButton("text:=OK").Click
If(window("text:=Flight Reservation").Dialog("text:=Open Order").Dialog("text:=Flight Reservation").exist)then
window("text:=Flight Reservation").Dialog("text:=Open Order").WinButton("text:=Cancel").Click
datatable(2,1)="Not Exist"
Else
datatable(2,1)="Exist"
End If
Next
Datatable.Export ("C:\flights.xls")
window("text:=Flight Reservation").Close


Before running this script, in "example.xls" you have to put two columns.
one is OrderNo and one is Result.
In OrderNo you can enter any valid or invalid OrderNo's and Result you can leave as it is.
We will out put the data into Results.

What is Input Parameters and OutPut Parameters

Input parameter allows you to run a test using different set of data input values.
When you use a datatable parameter, you must instruct QuickTest on where the input data will come from.

An output parameter is a value which comes back from the application under test. When you run the test QuickTest retrieves the current value of the property and enters it in the run-time datatable as an output value.

You can subsequently use this output value as a input value in your test. We call this data correlation. This enables you to use data retrieved during other parts of test.

How to run the batch file through Script

I have taken 3 tests as a example for doing batch run. They are

1. Display -It will display a message in a word doc.
2. DisplayDate - It will display a date and time in a Notepad
3. Multiplication - It will display a mathematical table in Notepad

I converted them in respective funcitons and saved in notepad as a .vbs file.
(in C:\VBLibraryFiles\)
And i wrote a VBS Finction that is called above 3 functions and saved as a callAll.vbs
(in C:\VBLibraryFiles\)
Before running the test I loaded all files into resource tab

callAll() 'Here i am just calling callAll function which is defined in callAll.vbs file

**********************

Display.vbs -

public funciton display()

set WordObj = CreateObject("Word.Application")
WordObj.visible = true
Set wordDoc = WordObj.Documents.Add
WordDoc.Range.InsertBefore "Hi Good Morning"
WordDoc.SaveAs "C:\Greetings.doc"
WordDoc.quit
Set wordObj = Nothing

End Function

***********************

DisplayDate.Vbs -

Public Function displayDate()

Set fso = createObject("Scripting.filesystemObject")
Set fptr = fso.createTextfile("C:\Sample.txt")
a = FormatDateTime(Date,1)
fptr.writeLine a

End Function

*******************************

Multiplication.Vbs -

Public Function multiplication()

Set obj = createObject("Scripting.filesystemObject")
Set of = obj.createTextFile("C:\mat.txt")
For i=1 to 10
x=5*1
of.writeLine "5 * "&i&" = "&x
Next

End Function

*****************************

CallAll.Vbs -

Public Function callAll()

display()
msgbox "Test 1 is pass"
displayDate()
msgbox "Test 2 is pass"
multiplication()
msgbox "Test 3 is pass"

End Function

How to copy the file from one location to another location

dim filesys
Set filesys=CreateObject("Scripting.FileSystemObject")
If filesys.FileExists("C:\sourcefolder\anyfile.ext") then
filesys.CopyFile "C:\sourcefolder\anyfile.ext", C:\destinationfolder\"
End If

How to get the Count of each file in a particual folder

Set fso = CreateObject("Scripting.FileSystemObject")
Set fold = fso.getFolder("D:\testingfiles")
Set fc = fold.files

word=0
xls=0
txt=0

datatable.getSheet(1).addParameter "Word",""
datatable.getSheet(1).addParameter "Excel",""
datatable.getSheet(1).addParameter "text",""
datatable.getSheet(1).addParameter "Total Files",""

For each f in fold.files

if lcase(right(f.name,4)) = ".doc" then
word=word+1
end if

if lcase(right(f.name,4))= ".xls" then
xls=xls+1
end if

if lcase(right(f.name,4))= ".txt" then
txt=txt+1
end if
next

datatable(1,1)=word
datatable(2,1)=xls
datatable(3,1)=txt
datatable(4,1)=fc.count

'Run this script and see the runtime datatable

Select RadioButton through Datatable

Browser("micClass:=Browser").Page("micClass:=Page").WebRadioGroup("name:=servClass").Select
Datatable("FlightClass, dtGlobalSheet)

'Here FlightClass is (Coach,Business, First) in the datatable.

How to Run and Close the application during Run time

We can Invoke the application during run session using

SystemUtil.Run "NameOfFile"

Systemutil.Run Statement enables you to open or run any application from a given location.
Similarly, you can use SystemUtil to close the application like this:

SystemUtil.CloseProcessByName "explorer.exe"

Working With Excell

Here I am discussing
How to create a Excel Sheet
Storing the data into Excel Sheet
Reading the data from Excel Sheet

Creation of Excel Sheet -

Set Excel=CreateObject("Excel.Activation")
Set ExcelSheet=CreateObject("Excel.sheet")
ExcelSheet.Application.visible=true

Storing the data into Excel Sheet -

Excel.ActiveSheet.Cells(1,1).Value="UserName"
Excel.ActiveSheet.Cells(1,2).Value="Password"
Excel.ActiveSheet.Cells(2,1).Value="arunsingh"
Excel.ActiveSheet.Cells(2,2).Value="rajaputra"
ExcelSheet.SaveAs "C:\text.xls"
datatable.Import "C:\text.xls" 'Importing excel sheet into datatable

Reading the data from Excel Sheet -

msgbox "UserName is="+Excel.ActiveSheet.Cells(2,1)
msgbox "Password is="+Excel.AcitveSheet.Cells(2,2)

How to Capture the Screen Shot

By using the below script we can capture the screen shot at run time -

Browser("BrowserName").Page("PageName").captureBitmap "c:\test\ScreeShot1.bmp"

Below example will help you to get familiar with this-
'Prerequisite: Open the FlightReservation Login screen
'Then Run this Script

Set Dlg=Dialog("text:=Login")
set Wnd=Window("text:=Flight Reseravation")
Set oDlg=wnd.Dialog("text:=Open Order")

Dlg.WinEdit("attached text:=Agent Name").set "rajaputra"
Dlg.WinEdit("attached text:=Password").setSecure "mercury"
Dlg.WinButton("text:=OK").Click

wait (7)

wnd.Activate
wnd.WinButton("window id:=5").Click
oDlg.WinCheckBox("text:=&Order No.").Set "ON"
oDlg.WinEdit("window id:=1016").set "100"
oDlg.WinButton("text:=OK").Click

if(oDlg.Dialog("text:=Flight Reservations").Exist) then
oDlg.Dialog("text:=Flight Reservations").CaptureBitmap "C:\ScreenShot.bmp"
oDlg.Dialog("text:=Flight Reservations").WinButton("text:=OK").Click
oDlg.WinButton("text:=Cancel").Click
End If

wnd.Close

Wednesday, June 4, 2008

What is Datatable

Data table assists you in parameterizing the test.
There are two type of Data tables are available in QTP.
1. Design time data table 2. Runtime Data table.

Design time Data table -

There are two type of data sheets available, they are 1. Global Data Sheet 2.Local Data Sheet
The Global Data Sheet contains the data that replaces parameters in each iteration of test.
Each time you add a new action to the test, a new action sheet (Local Sheet) added to the data table. It contained data, replaces parameter in only one iteration of the test.

Run time Data table -

During a run session, Quick test creates a runtime data table.
When the run session ends, the runtime data table closes, and the data table pane again displays the stored design time data table.
The final data from the runtime data table is displayed in the runtime data table in the test results window.

Mandatory - Assitive - Ordinal Identifier properties

Quick test identify the objects by learning the default property values is called mandatory properties.
Ex - attached text, native class, alt, html tag, image type.

If the mandatory properties are not sufficient to create a unique object description then Quick test uses Assistive properties of the object to identify uniquely.
Ex - Id

If the mandatory and assistive properties are not sufficient to create a unique object description then Quick test uses Ordinal identifier to create a unique description of the object.
Ex - index, location, creation time.

How to load the Object Repository

To load the object repository at runtime -
Write following script...

Set app=CreateObject("QuickTest.application")
app.test.settings.resources.ObjectRepositoryPath="Path of the Object Repository"


To load manually -

Goto Test-Settings-resources-select shared for Object Repository Type-Browse the required Object Repository.

What is Object Repository

Object Repository is a place where all recorded or added objects are stored.
When you record the application, recorded objects are stored in the Object Repository, in order to use them later.
Object Repository mainly identifies how it will recognize an object at the time of replay.
Object Repository displays a tree of all objects in the current component or in the current action or entire test (depending on the object repository mode you selected)
We can view or modify the test object description of any test in the repository or we can add new objects to the repository.
There are two types of Object Repositories : Per Action and Shared Action

When we are working in Object Repository, Per Action mode, Quick test creates a new object repository for each action.
When we are working in Object Repository, Shared Action mode, Quick test adds new objects to the object repository.
If we record operations on a object that already exists in the Shared Object Repository, Quick test uses the existing information, and does not add the object to the Object Repository.

How QTP Recognize the Objects in AUT

When we record the application, QTP interact with an object and stores Test object properties in its Object Repository.
When the test runs, QTP maps the Test Object properties with the Runtime Object properties.
If it successfully maps the runtime properties, then test passes.
If not, test fails.

Test Object Properties - are properties of an object in the Object Repository
Runtime Object Properties - are properties of an object in the application.

Runtime Object is the actual object to which a Test Object can be mapped.
It is the actual object present in your AUT.

Example -

Open a Notepad and add objects in Object Repository
Then write script in QTP...
Msgbox window("Notepad").GetTOProperty("height")
'It gives you empty message. Because you didn't add height in Object Repository.
'Now try this
Msgbox window("Notepad").GetROProperty("height")
'You will get the height of the notepad window.

For Test Object, you have to add the property then only it will show in the test object properties list.
But for Runtime Object, always all properties are available.

We can use SetTOProperty method to change the properties of the test object, But we cannot change the properties of the Runtime Object.

Tuesday, June 3, 2008

Smart Identification

When Quick test uses the recorded description, to identify the object, it searches for the object that matches every property value in description.
If Quick test unable to find any object that matches the recorded object description, or if it finds more than one object that fits description and uses the smart identification mechanism to try to identify the objects.

A smart identification mechanism can help Quick test to identify an object, even if recorded description fails due to changes in property values.
In Smart Identification we have to mention the set of base filter and optional filter properties to identify the object in the application.
Smart Identification is required only if mandatory, assistive properties are failed to recognize the object.


Base Filter - Fundamental properties of particular object, those whose values cannot be changed without changing the essence of original object.
Optional Filter - Other properties can help to identify objects of a particular class as they are unlikely to change on a regular basis but which can be ignored if they are no longer applicable.

Library Files

Library files are containing normal VB Script code.
We can load library files by using 2 ways -

1. Choose Test-Settings-Resources tab-Click on + button - browse and select library file-click OK
2. Use Executefile function to load library files at run time.

When we associate a library file with the test, then all functions with in the library are available to the actions presents in the test.
But when we use executefile function to load a library file, then the functions with in the library file are restricted to a specific action.


Ex: ExecuteFile "FilePath"

Sample Script:

execute file "C:\sample.vbs"
x=10
y=5
result=SumofTwoNumbers(x,y)
msgbox (result)

Code in Sample.vbs -

Public Function SumOfTwoNumbers(a,b)
Dim sum
sum=a+b
SumOfTwoNumbers=sum
End Function

Error Handling

Error handling enables us to convert system generated error messages to user defined messages.

"On Error Resume Next" should be used when you know if an error is expected and don't want to raise it. You may want to do different actions depending upon the error that occurred.

Use err.number and err.description to get more details about the error.

How to handle the exceptions

By using Recovery Scenario Manager, we can handle the exceptions occurred while running the test.

Recovery is a concept like exception handling in a programming language, which can be applied when an unexpected failure occurs.


When TO Use:
We should use Recovery Scenario only for unpredictable events, or events that cannot synchronize with a specific step in our test.

4 Exceptions in QTP:
1. Popup Window - A popup window appears in an open application during a test run.
2. Object State - Property of the object changes its state or value.
3. Run Error - A step in the test does not run successfully
4. Application Crash - An open application fails during a test run.

3 Types of Recovery Scenarios:
1. Triggered Events - Trigger is nothing but the cause for initiating the recovery scenario.
2. Recovery Steps - It defines what needs to be done, when recovery scenario has been triggered.
3. Post Recovery Test Run - It defines what need to be done after the recovery action has been taken. It could be repeat the step or move to next step etc..

Monday, June 2, 2008

About Parameterization

To data drive we have to parameterize.
Through parameterization only we can drive a transaction with different set of data.

Parameterization:
When we test the application, we may want to check how it performs the same operations with multiple set of data.
In parameterization, data can be typed or import from database, spread sheet or text files.

4 Types of parameters:
1. Test, Action parameter - enable you to use values passed from the test or values from other actions in our test.
2. Data table parameter - enable you to create a data driven test, that runs several times using the data you supply. In each iteration quick test uses a different value from the datatable.
3. Environment Variable parameter - enable you to use values from other sources during run session.
4. Random Number Parameter - enable you to insert random numbers as values in our test.
Ex: RandomNumber(0,20)

Saturday, May 31, 2008

To Count the no of objects in a Web Page

'Open a Google page and count the no of links and buttons in that page

If Browser("index:=0").Exist(1) then 'If Browser is already opened
a=Browser(index:=0").GetROProperty("hwnd")
Browser("hwnd:="&a).Navigate("http://www.google.com")
Browser("hwnd:="&a).Sync
wait(2)
Else 'If Browser is not opened
Systemutil.Run "IEXPLORE.exe"
a=Browser("index:=0").GetROProperty("hwnd")
Browser("hwnd:="&a).Navigate("http://www.google.com")
Browser("hwnd:="&a).Sync
wait(2)
End If

Set butObj=Description.Create ''''For Buttons
butObj("html tag").value="INPUT"
butObj("type").vlaue="submit"

Set linkObj=Description.Create ''''For Links
linkObj("html tag").value="A"

Set Buttons=browser("hwnd:=&a).page(title:=.*") .ChildObjects(butObj)
Set Links=browser("hwnd:=&a).page(title:=.*") .ChildObjects(linkObj)

msgbox "Total Button are: "&Buttons.count
msgbox " Total Links are: "&Links.count

Option Explicit

When you use the Option Explicit statement, you must explicitly declare all variables using the Dim, Private, Public, or ReDim statements.
If you attempt to use an undeclared variable name, an error occurs.
VB Script in general doesn't need variable declaration. Without using Dim, a variable can be directly used for assigning. For ex - temp=1
However, such practice can always be error prone. Ex: If i want to use the same variable in some other statement and miss spell it, say tempe=temp+1
VB Script still considers "tempe" as valid. In this case if we use Option Explicit on top of our script and proceed, then application will not proceed unless until u declare each and every variable.
Hence you make sure that your variable is serving your purpose.

Test Object Model

Test Object Model is the model that QTP uses to recognize objects in the application.
Every object has a set of properties and attributes which QTP uses to perform the operations.
Also using these attributes in form of mandatory and assistive properties, QTP recognize the particular object.

Automation Object Model

Quick test Automation Object Model is used to automate the quick test operations.
For example, if you want to run a test in QTP you have to follow these steps -

'i. Open a QTP
Set qtApp=CreateObject("Quicktest.Application")
qtApp.Launch
qtApp.visible=true
'ii. Open a test in a QTP
qtApp.open "testpath", true
'iii. Specify the result folder
Set qtTest=qtApp.test
Set qtResults=CreateObject("Quicktest.runreslutoption")
qtResults.ResultLocation="resultpath"
'iv. Run the test
qtTest.run qtResults
'v. Close QTP or Open another test and run it
qtTest.close
qtTest.open"TestPath", true

Before going to Automation

Before going to Automation, there is a process -

1. Whether we have to go for automation.
2. What are the client requirement for automation.
3. Which tool we have to use for automation
4. Gathering suggestions from others and searching for the resources.
5. Identifying the application components to be Automated.
6. Preparing the automation approach document (Which list the Functionalities, Risks, Assumptions, Tool Identification, and Proof of Concept functionalities)
7. Gathering the test cases for automation
8. Giving trainings
9. Resource allocation.

Environment Variables

Environment variables helps us to use the variables from other sources during the run session.

Types of Environment Variable:

1. User defined Internal - These variables are saved with in the test and accessible only with in the test in which they were defined.
2. User defined External - We can use external environment variables from any other program.
Example for User Defined Environment Variables is Email, FirstName,LastName, PhoneNumber, etc..
3. Built In - It enables you to know the current information about the test and computer on which the test is run. These variables are accessible from all test and components. They are read only.
Example for Built In Environment Variable is OperatingSystem, OSVersion, LocalHostName, ProductName, ProductVersion, etc..

By default, Environment variables are internal type that means we cannot use that internal environment variables from any other program. That's why we can make it as external variables.

Deference between Built In and User Defined Environment Variables -

We cannot create or modified the values for built in environment variables. But we can create and modify the values for user-defined environment variables.

Use of Environment variable -

Environment variable comes into picture when we try to parameterize data.
It is one kind of data source.
When we want to test an application, where the user interface string changes, depending on the selected language.
We can use external environment variables from any other program by loading xml file.
Ex: Environment.LoadFromFile"Path of the xml file"

To check whether it is exist or not -

By using "Environment("ParamterName").value" we can know that variable exist in the environment.
By using "Environment.value("ParameterName")" then QTP will create a new internal environment variable if does not exists already.




Function Vs Action

If we want to use the Object Repository feature then we have to go for Actions
If the functionality is not about any automation script we can go for functions.
(Example, a function like getting a string between two specific characters, now this is something not specific to QTP and can be done by pure VB Script, so this should be done in a function not an action.)

About Functions

Function is a group of methods and instruction and it can be access by calling that function.

User defined functions can be coded as part of QTP files or can be coded as separate ".vbs" files.
These can be associated as library files under Run Settings. This would enable you to create a library functions which can be used across scripts as and when required.

Example for User Defined Function for WebEdit Class:

Public function edit(name) 'Defining the function
Browser("BrowserName").Page("PageName").WebEdit("User ID").set name
End Function

Call edit("rajaputra") 'Calling the function

Descriptive Programming

If the object is not in the object repository, then based on the unique property of the object we can write a program on that object. It is nothing but Descriptive Programming.

QTP cannot take an action on a object until unless its object description is in the Object Repository.
But Descriptive programming provides a way to perform action on objects which are not in Object Repository.

When to Use:

1. The object in the application are dynamic in nature and need special handling to identify the object.
2. When object repository is getting huge due to the no of objects being added. If the size of the object repository increases too much then it decreases the performance of QTP while recognizing the object.

Example for when to use DP:

Suppose, we have an application that has not been developed yet.
Now QTP recording the script and adding the objects to the object repository needs the application to be up. That would mean waiting for the application to be deployed.
But if we know the description of the objects that will be created then we can still start of with the script writing for testing.

How to write Descriptive Programming:

There are two ways to write.
1. By creating the properties collection objects for the description.

To use this method you need to create an empty description
Set ObjDesc=Description.Create 'Now we have blank description in ObjDesc.
'Each description has 3 properties, they are Name, Value, RegularExpression.
ObjDesc("PropertyName").Value="Value of the Property"
'When you use the property name for the first time the property is added to the collection and 'when you use it again the property is modified. Now we can use it as ....
Browser("BrowserName").Page(PageName).WebEdit(ObjDesc) .set "Test"

'To Remove the property from the collections -
ObjDesc.remove"PropertyName"

'To know the property exist or not in the property collection -
If ObjDesc("PropertyName").value=empty then
msgbox "Not Exist"
else
msgbox "Exist"

2. By giving the description in form of the string arguments.

Browser("PropertyName:=PropertyValue").Page ("PropertyName: =PropertyValue")..........

About Actions

Action is used to split out test script into more flexible and logic unit.

When it is used:

If we require a particular step of our test scripts then we can use action by making it reusable action.
If two or more test require the same script then we go for the actions.

Action Types:

1. Non Reusable Action -It can be called only once in our test. It cannot be called in any other test.
2. Reusable Action - It can be called multiple times in our test as well as in other test.
When it is called in other test then it becomes External Action.

By default each action is non reusable action. If we want to convert it as reusable action then there are two ways:
1. Select Action, write click, select the check box reusable action
2. Select Action Properties, select check box reusable action

(From keyword view both methods will be possible. But from expert view only 2nd method is possible.)

By making action as a reusable action, we can call that actions from other tests, rather than recording, modifying, and enhancing the same steps each time.

How to call an Action:

By using "Call to copy" or "Call to Existing" we can call the actions in QTP.

Defference betweeen Call to Copy and Call to Existing:

Call to Copy:
1. It is read and write mode
2. We can call both reusable actions and non reusable actions.
3. If we make any changes in base program, that will not be effected to the copied program

Call to Existing:
1. It is read only mode
2. We can call both reusable actions and non reusable actions.
3. If we make any changes in base program, that will not be effected to the copied program.

Wednesday, May 28, 2008

How to Write Script

Here I am giving an idea of how we can write the script in different ways
Here I am taking an example to write a statement to click on a specified button.
I took two conditions, first one is when we are using object repository, second one is when we are not using object repository (Using Descriptive Programming)

Using Object Repository:

'1st Method -
Window("Flight Reservation").WinButton("Update Order").click 'Common Method

'2nd Method -
Set wndObject=Window("Flight Reservation") 'Assigning window object to an object variable
wndObject.WinButton("Update Order").click
OR
Set btnObject=Window("Flight Reservation").WinButton("Update Order") 'Assigning button 'object to an object variable

'3rd Method -
With Window("Flight Reservation") 'Using with statement
.WinButtton("Update Order").click
End with

Usingh Descriptive Programming :

'4th Method -
Window("text:=Flight Reservation").WinButton("text:=&Update Order").click

'5th Method
Set oDes=Description.Create 'Creating a description Object
oDes("nativeclass").value=Button 'Assigning description to the description object
oDes("text").value="&Update Order"
Window("text:=Flight Reservation").WinButton(oDes).click 'Clicking on button using the 'created description object

'6th Method -
Set oDes=Description.Create 'Creating a description Object
set btnObjList=Window("text:=Flight Reservation").childObjects(oDes) 'Filtering objects
For objIndex=0 to btnObjList.count-1
propVal=btnObjList(objIndex).getROProperty("text") 'Get Property value from object
If propVal="&Update Order" then 'Compare Property value
btnObjList(objIndex).click 'Click on identified object
Exit for 'Exit for loop after clicking on the button
End if
Next

'7th Method -
Public const wndFlight="text:=Flight Reservation" 'Assigning a window object to a constant
Public const btnUpdate="text:=&Update Order" 'Assigning a button object to a constant
window(wndFlight).WinButton(btnUpdate).click 'clicking on a button using constants

About Me

My photo
Hi all,I am Arun Singh Rajaputra. I am working as a Project Lead in a reputed organization in Hyderabad, AP, India. I have little bit knowledge on Quick Test Professional and like to share my knowledge to all through this blog.

Subscribe to get updates on this blog

Enter your email address:

NOTE

Some of the posts posted in this blog are collected and most of them have been prepared by me. If any one have objections regarding any copied posts. Please mail me so that I can take a necessary action on that post.