Blog to understand automation concepts in QTP, Selenium Webdriver and Manual Testing concepts

Showing posts with label Test Scripts. Show all posts
Showing posts with label Test Scripts. Show all posts

All about working with browser object in QTP

This article discusses some useful code snippets working with browser object in QTP and useful tips while working with browser in QTP.

1.  How to launch a webpage in any of the browser.

Well, there are multiple ways to launch a webpage in browser of choice

a.  Using Systemutil command - SystemUtil.Run is an inbuilt QTP command used to launch an application. We can launch a browser using Systemutil as:

                  SystemUtil.Run "Chrome.exe", “http://www.thoughtscollectionme.blogspot.in/

Using systemutil.run we can launch other application, e.g.: we can open a word document

                  SystemUtil.run “winword.exe”, “C:\meraword.docx”

Other methods for Systemutil command are:

CloseProcessByName: Closes the process based on the name of the process. E.g.: If we want to close chrome in the machine, we can use:
                 SystemUtil.CloseProcessByName "chrome.exe"

CloseProcessByHwnd: Closes the process based on the window handle of the process.
                  SystemUtil.CloseProcessByHWND handleid

b.  Another method is to launch the browser using Wscript.shell object. The code to launch the application using wscript.shell object is as follows:

                 Set objShell = CreateObject("Wscript.shell")
                 objShell.run “chrome.exe  http://www.thoughtscollectionme.blogspot.in/
                 set objShell = Nothing

    2. How to know how many browsers instances are open at a particular instance:

We can get the number of open instance of browser using below function
  Function getbrowsercount()
               ‘’Create an object of description class
              Set objBrowser = Description.Create
             ‘’ We have created an description object with micclass as browser
             ObjBrowser(“micclass”).Value = “Browser”
            ‘’objbr stores collection of objects which matches property of micclass as browser
             Set objbr = Desktop.ChildObjects(ObjBrowser)
           ‘’ return the count of browsers in the function itself.
            getbrowsercount = objbr.count
            End Function

3. How to know the title of each of the  open browser

     Set objBrowser = Description.Create
    ObjBrowser(“micclass”).Value = “Browser”
    Set objbr = Desktop.ChildObjects(ObjectBrowser)
    getbrowsercount = objbr.count
    For i= 1 to objbr.count
   ’’Loop through each of the browser and print the title of browser in message box
            Msgbox objbr(i).getRoproperty(“title”)
    Next

    4. Now we need to close all the open browsers?

  ‘’We use ordinal identifier to identify an test object by assigning a numerical    value which indicates object’s  location or order relative to its group. Different types of Ordinal identifier are:
·         Index
·         Location
·         CreationTime.
While Browser(“Creationtime:=0”).exist(0)
Browser("creationtime:=0").Close
Wend

 5. How to close all browser except Quality Center?

When we run a test in QTP, we do not require QC to close but other browsers to close. The code can easily be derived using the codes explained above.
The code will be something like:
Function CloseAllbrowsersExceptIE(browsertitle)
Set objBrowser = Description.Create
objBrowser("micclass").Value = "Browser"
'Get all browsers
Set objBrowserLst= Desktop.ChildObjects(objBrowser)
For i=0 to objBrowserLst.count-1  
 'Verify the title of the browser contains "Quality Center"  
If InStr(objBrowserLst(i).GetROProperty("title"), "Quality Center”) = 0 Then
                                objBrowserLst(i).close  
            End If  
            Next 
Set objBrowser = nothing
Set objBrowser = nothing
End Function

6. Next question is how to close only a particular browser only and keeping the other browsers open.


The code is very much similar to above problem where we close all the browser except QC.
Just need to change the if statement in the code above:

If InStr(objBrowserLst(i).GetROProperty("title"), "Quality Center”) = 0
to
If InStr(objBrowserLst(i).GetROProperty("title"), "Quality Center”) > 0

will close only the particular browser and keep the other browser open.


Example to explain working with excel application in QTP using VBScript

 In this post, we will know how to work with excel application with an example . We will explain how to copy a source file and create an destination file with same name or a dynamic name generated. We will also explain how to copy data from an excel worksheet to another worksheet, delete an excel sheet, and rename an excel worksheet using excel application object.

 The problem we will resolve using this code is as follows. 


In the below code, we will explain how to implement the above using vb script.

destfile = CopyFile("D:\testt\TestSupport_1.xls", "D:\testt\", 1)
copydata "D:\testt\generatedRpt.xls", destfile, "general_report", "temp"
masterfile = Copyfile(destfile, "D:\testt\TestingSupport_Daily_Data.xls",0)


'' Description - This function will copy the file from source location to destination folder. In this example we have used below three parameter as per our need.

''Source file - Exact name and location of the source file. This is an external file generated at a fixed location which was first part of problem and will be handled using QTP
''DestinationFolder - this is either the folder location with or without file name. 
''filename - this shows filename is included in the the destinationfolder. In case of dynamic naming of the file, provide value as 1 else provide value as 0.

function CopyFile(SourceFile, DestinationFolder, filename)
if (filename =1) then
'' generate a dynamic name for the file in case filename argument is provided as 1
    DestinationFile = DestinationFolder + "TestSupport" + cstr(DatePart("m",Now()))+ cstr(DatePart("d",Now()))+ cstr(DatePart("yyyy",Now())) + ".xls"
else
   DestinationFile = Destinationfolder
end If

    Set fso = CreateObject("Scripting.FileSystemObject")
    'Check to see if the file already exists in the destination folder
    If fso.FileExists(DestinationFile) Then
    ''In case of destinationfile already exists, delete the existing file
fso.DeleteFile DestinationFile, True
    End If

'' Copy the file from source location to destination location
    fso.CopyFile SourceFile, DestinationFile, True
''close the instance of filesystem object
    Set fso = Nothing
''return the value of file name as the rsturn value of the function.
copyfile = Destinationfile
End function
'

'' Description - this function will copy data from sheet1 of workbook1 to sheet2 of workbook2.


sub copydata(workbook1, workbook2, sheet1,sheet2)
'' Create an instance of excel object
Set objExcel = CreateObject("Excel.Application") 
'' define if the excel needs to be displayed and alerts to be displayed. here the excel will be visible but no alerts will be displayed in case of alert prompt in the excel application.

objExcel.Visible = True
objExcel.DisplayAlerts = False
'' create an instance of excel workbooks for source as well as destination workbook
Set objsrcFile= objExcel.Workbooks.Open(workbook1)   
Set objdestfile = objExcel.Workbooks.Open(workbook2) 
objsrcfile.Activate
'' create instance of worksheet in the workbook
Set objsrcSheet = objsrcfile.Worksheets(sheet1)
Set objdestSheet = objdestfile.Worksheets(sheet2)
'' gather the data from the source file to destination file
'' In the below example , we are copying the data from 4th row in source file to destination file. we can start from first row also if required.
icolcount = objsrcSheet.usedrange.columns.count
irowcount = objsrcSheet.usedrange.rows.count
for i = 4 to irowcount-1
for j = 1 to icolcount-1
''copies data from the destination file to the source file
objdestSheet.cells(i-3,j)= objsrcsheet.cells(i,j)
next
next
objsrcfile.save
objdestfile.save
''This is again a customised code to delete a sheet from excel file. 
objdestfile.sheets("Previous Day").Delete
'' This step renames the sheet in the destinstion file.
Set objWrksheet = objdestfile.Worksheets("Today")
objWrksheet.Name = "Previous Day"
set objWrkSheet = nothing
''Rename another sheet in the workbook
Set objWrksheet = objdestfile.Worksheets("temp")
objWrkSheet.Name = "Today"
set objWrkSheet = nothing
''Add a temp table at the end of sheets and name it as temp
Set objWrkSheet = objdestfile.Sheets.Add(, objdestfile.Sheets(objdestfile.Sheets.Count))
objWrkSheet.Name = "temp"

''Save the excel file and close the instance of excel aplication
objdestfile.save
objsrcfile.close
objdestfile.close
objexcel.quit
set objexcel = nothing
msgbox "done"
end sub

How to send e-mail using outlook object in QTP

This post explain how to send e-mail using microsoft outlook object with or without any attachments. In the next article we will explain how to read information from an e-mail message.

''Function Description - This function sends a mail to end user
'' Arguments - SendtoUser - Mail will be send to user mentioned in send to
''Subject - Subject of the mail
''Body - Text of the mail
''Attachment - Path of attachment to send e-mail

SendMailUsingOutlook "SendToUser@test.com; testZ@test.com"," Subject", "Body", ""

Function SendMailUsingOutlook(SendToUser, Subject, Body, Attachment) 

'' create an object of outlook application and creating a new e-mail object
    Set objOutlook=CreateObject("Outlook.Application") 
    Set objMail=objOutlook.CreateItem(0) 

'' Provide details of the mail object
    objMail.to=SendToUser
    objMail.Subject=Subject 
    objMail.Body=Body 

'' attach a file with the e-mail, provide path of the attachment in the folder
    If (Attachment <> "") Then 
        objMail.Attachments.Add(Attachment) 
    End If 
'' Send the e-mail
    objMail.Send 
'' close the instance of Outlook application object
    objOutlook.Quit 

''release the object created    Set objMail = Nothing 
    Set objOutlook = Nothing 
End Function 

Tutorial about Array in VBScript for QTP

Array is a data type used to describe a collection of elements. An array can be one-dimensional or multidimensional array. In VBScript, array can be represented as follows:


Dim arrayOned(6) - represent a dimension array which can store 7 elements. Index starts from 0.
Dim arraytwod(6)(4) - represents a two dimensional array which can store 7*5 =35 element
Dim(6)(4)(5) - Represents a three dimensional array. We can describe  n-dimension array in similar ways.

The above arrays are example of fixed array. Once we specify an array with dim and providing size of array, it is created as fixed dimension array. We cannot change the size of the array.
We can also create dynamic array in VBScript as shown below:

dim arraydynam() - create a variable without providing the size of array.Redim arraydynam(10) - we can then assign a size to the array by using redim. We can resize the array size as when required. 


On reducing the size of the array, loss of information can take place, so care should be taken while reducing the size of array in dynamic array.


There are some useful inbuilt functions in VBScript used to work with arrays. Let us discuss on the same.


Split Function - Split can be used to split a string into array based on the delimiter provided. Syntax for Split function is:

Split (expression [, delimiter [, count [, compare]]]) - here expression denotes the string which will be splitted based on the delimiter provided. 
Count and compare are optional with default value as -1 (repeats all substring) and binary compare. Default delimiter used is space.

Ubound function - Ubound returns largest subscript for the provided dimension of an array. In Case of argument for dimension not provided, it gives the ubound for first dimension

UBound(array, dimension))

Lbound function - Lbound returns smallest subscript for the provided dimension of an array. In Case of argument for dimension not provided, it gives the lbound for first dimension

UBound(array, dimension))

Join Function - Join function does opposite of what Split function does. It joins all the elements in the array using the delimiter. Syntax of function is:Join(array, delimiter)

In case of join also, the default delimiter if not provided is space character.

Filter Function - Filter is used to create a sub array from array matching the particular condition.
Filter(array, value, include, compare) - In the function, include and compare are optional parameters, include can have value true or false, true for searching for element with particular value matching and false to return elements which do not have match the condition

Array function - This function creates an array based on array element provided in the argument.

e.g. : a = array ("testing ", "array", "by" ,"creating", "array", "using array functions)

IsArray function returns true/false that indicates whether a specified variable is an array or not


''A simple code explaining the various functions for array manipulation

dim arr, strjoin
arr = split("this,is, wonderfrul, test",",") ' create an array using split function
ilowbound = lbound(arr) 'get lowerbound and upperbound for array
iupperbnd = ubound(arr)
for i=ilowboud to iupperbnd Step 1 '' Loop the array element
msgbox arr(i)
Next
b= filter(arr, "t")
msgbox b(1)
strjoin = join(arr, ";")
msgbox strjoin
msgbox Isarray(arr)

VB Script tutorial - Variables, Constants and Arrays

VBScript is used extensively with QTP for creating test script. With articles on VBScript, I will try to explain the VBscript and refresh the concepts for my self knowledge.
In VBscript, variables of all the data types are declared with the same data type called as variant


A variable can be defined as Dim abc. We may or may not need to define the variable explicitly. If we require every variable used must be defined. we need to provide option explicit.
Using Option explicit is a good practice as it keeps a check on the variables used in the script

Some Important point to note about variable declaration are :

  • Variable for all the data type are defined as dim in vbscript
  • VBScript is not case sensitive, therefore variable abc and ABC are the same.
  • If Option explicit statement is defined, each of the variables used in the vbs file must be declared before use.
  • A variable must start with alphabet and should not exceed 255 characters
  • We can define variable everywhere in the script but it is best to define all the variable at the start of the function or script for better maintenance of variables
  • We can ignore standard naming convention by defining the variable within square bracket but should avoid this.
  • Multiple variable can be defined as Dim abc,def,qrtin 
We can also define an array variable, to store a set of values in a variable. An array can be one dimensional or multidimensional;'' For e.g. in below example we define the fixed size array, on trying on resize the array, it gives us error.
dim arra(5)
An array can be defined as dynamic array, we can resize the array then, below code explains how to create a dynamic array. Preserve is used to preserve value 
dim arrad() '' define a dynamic array variable without size provided
An variable defined at a function level can be used within the function in which it is defined. A variable defined at script level, can be used across the functions within the script. 
const abcd = 3

Option explicit
dim abc
abc = 3
msgbox abc



Dim [1Test 231]
[1Test 231] = "I have defined a variable not starting with alphabet and having a space in between"
msgbox [1Test 231]

An array can be a fixed size array defined as dim arra(5) , this will store 6 elements, but once defined the array size can not be modified. 


redim arra(3) 
arra(0) = 54 
msgbox arra(0)


redim arrad(3) '' Using Redim, we can define the size of the array. 
arrad(3) = 75  
redim preserve arrad(5) '' we use preserve the values stored on existing array using preserve as shown here. In this example we resized the array size to 5 and preserved the original value stored in array.
msgbox arrad(3)
We can also create multiple dimension array as dim arram(4)(5)(6).

In QTP, we can also define environment variable to be used across the actions.


Another type of variable in constant. A constant variable does not change its value once defined. Also value cannot to assigned to a constant post declaration of constant and its value

abcd = 43
msgbox abcd

How to compare 2 dictionary object and report the differences in QTP results

This post discusses how to compare two dictionary objects and display the difference between the values in two dictionary objects in table format in QTP results using Reporter.logevent.


''function to compare two Dictionaries 

Public Function Comfunct_CompareDictionary(ObjDictBase, ObjDictGen)

Comfunct_CompareDictionary = True 
''Check if both dictionary objects have the same number of items
If ObjDictBase.Count <> ObjDictGen.Count Then
Reporter.reportevent micFail,"Data in Dictionary 1 and 2","Data mismatch in the dictionary. there are " & objDictBase.Count & "records in dictionary 1 compared to " & objDictGen.Count & "records in dictionary 2" 
Comfunct_CompareDictionary = False
Exit Function
End If
''Compare keys and values
arrKeys = ObjDictBase.Keys
''Create a table for the differences
strTable = "<table border=""""2""""><tr><td>Key Name</td><td><Value in Dictionary 1</td><td><Value in Dictionary 2</td></tr>"
For i = 0 to uBound(arrKeys)
''Compare key names in both dictionaries and validate keys in one dictionary exists in other dictionary
  If Not ObjDictGen.Exists(arrKeys(i)) Then
''ObjDictBase has a key which ObjDictGen doesn't have, hence exiting the function
Comfunct_CompareDictionary = False
Reporter.ReportEvent micFail, "Key " & arrKeys(i) & " exists in dictionary 1 but not in dictionary 2, " Key difference in both dictionaries"
Exit Function 
  End If
  ''Compare value of each keys in both dictionary and display the difference between 2 dictionary in Qtp results 
  If ObjDictBase(arrKeys(i)) <> ObjDictGen(arrKeys(i)) Then
''ObjDictBase value for arrKeys(i) differs from ObjDictGen, then log the difference in the table created above
Comfunct_CompareDictionary = False
strTable = strTable & "<tr><td>" & arrkeys(i) & "</td><td>" & ObjDictBase(arrKeys(i)) & "</td><td>" & ObjDictGen(arrKeys(i)) & "/td></tr>" 
  End If
Next
If Comfunct_CompareDictionary = True Then
Reporter.ReportEvent micPass, "Comparision of dictionary 1 and dictionary 2","Both dictionary matches"
Else
strTable = strTable & "</Table>"
''Compare value of each keys in both dictionary and display the difference between 2 dictionary in Qtp results 
Call reportinQTPhtmlContent(strTable)
End If 
End Function


''Function to report in QTP result in table format

Public Function reportinQTPhtmlContent(strTable)
Set objdict = CreateObject("Scripting.dictionary")
objdict.Add "Status", micdone
objdict.Add "NodeName", "Table Data"
objdict.Add ("StepHtmlInfo"), strTable
Reporter.LogEvent "User", objdict, Reporter.GetContext
End function


Manipulating Array with examples using vbscript in QTP

In this post we discusses examples working with arrays and manipulating them in vbscript:

1.How to count number of elements in an array


intcount = ubound(arrayname)

2. How to join all the values in an array to a string and display the value in messagebox


dl=Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")
daysinWeek = join(dl, " ")
msgbox "days in weeks " & daysinWeek


3. How to split values in a string in an array based on delimiter


dl="Sunday>Monday>Tuesday>Wednesday>Thursday>Friday>Saturday"
daysinWeek = split(dl, ">")

This method can be used on looping as shown in example below:

On error resume next

Set objDesc= Description.create

'Set of Property values are delimited by "," 

If (instr(1,strDescObj,",") >0) Then

''Split multiple links based on delimiter.

arrDesc = split(strDescObj,",")

intPropSet = Ubound(arrDesc)

''Loop through each of the link and click the required link

for i = 0 to intPropSet

strDesc = split(arrDesc(i),"|")

objDesc(strDesc(0)).value = strDesc(1)

Next

End If



Understanding Date time function: Using VBScript in QTP

Below are some of the useful function for working with date/time in vb script. We will use the functions and illustrate where the functions can be used.


1. Date - This returns the current date of the system.


2. Now - This returns the current Date and time of the system.So now contains time part as well as date part while date function returns only date.


3. Time - This returns the current time of the system. So in terms of relation between date , time, and now function 


Now = date + time

4. Year, Month, Day, hour, minute, second - These functions return year, month,day,hour,minute,second part for the expression.


example : day(now) or  minute(now)

Above functions discussed above are useful for timestamp , and also for generating a unique number based on the function used.


5. Timer - Timer returns the number of seconds from 12:00a.m. This function is very useful for evaluating time spent in performing an activity by taking timer at the start and end of the activity and subtracting the time between two.


6. DatePart - returns specific part of the date .Possible values or part of date , that can be extracted as shown below:

  • yyyy - Year
  • q - Quarter
  • m - Month
  • y - Day of year
  • d - Day
  • w - Weekday
  • ww - Week of year
  • h - Hour
  • n - Minute
  • s - Second
Syntax of the function is : DatePart("m",d))where d is the date as "2013-06-09" and m will return the month of the date.

7. DateDiff - Returns the difference between two dates: 

Syntax : DateDiff(interval,date1,date2). Interval can be yyyy,q,m, y,d,.... as discussed earlier.


8. DateAdd - Add specified date to the date.

Syntax : DateAdd(interval,number,date)


VB Script functions to manipulate strings in QTP

We should know the useful vb script function to manipulate strings. In this post, we will discuss some of the vb script function to manipulate strings and how they can be used in codes:

1. Instr searches for a string within another another string and returns the location of occurrence of one string within another string.It returns the position of first occurrence of the string.This function is used if we need to verify if a particular text appears in a string.


Syntax : InStr([start,]string1,string2[,compare])


Example - Report and loop in case a particular text in not found in the string :

If (Instr(1, string1, string2)>0) Then
    Reporter.ReportEvent micpass , "string 2 is found in string 1","As expected"
Else
    Reporter.ReportEvent micfail , "string 2 is  found in string 1","string 2 is not found in string1"
End If

2. InstrRev is similar to instr and can be used for similar purposes, with only difference search starts from the end of string, although count returned is from start of string.


InStrRev(string1,string2[,start[,compare]])


3. Trim , lTrim, Rtrim removes characters from both left and right, only left and only right respectively blank spaces.


4. Left , Right, and Mid returns a specified character from left, right, and middle of the string. 


Mid(string,start[,length])

5. len returns number of characters in the string.


6. Split splits a string based on the delimiter in the function.


Example - How to find the total number of occurrence of a string in another string.By default, string2 has value space if not provided.

arrString = split(string1,string2)
totOccurence = ubound(arrString)

Example- Total number of words in a string.

arrString = split(string1)
totOccurence = ubound(arrString)