Search This Blog

Welcome to Machers Blog

Blogging the world of Technology and Testing which help people to build their career.

Wednesday, December 16, 2009

Some Basic Useful re-usable Scripts in QTP

General Functions which might be useful in the projects:-

Array BasicsSome basic info about creating and using arrays.' The easiest way create an array is to simply declare it as followsDim strCustomers()' Another method is to define a variable and then set it as an array afterwardsDim strStaffstrStaff = Array("Alan","Brian","Chris")' Yet another way is to use the split command to create and populate the arrayDim strProductArraystrProductArray = "Keyboards,Laptops,Monitors"strProductArray = Split(strProductArray, ",")' To itterate through the contents of an array you can use the For Each loopDim strItemFor Each strItem In strProductArrayMsgBox strItemNext' This will also itterate through the loopDim intCountFor intCount = LBound(strProductArray) To UBound(strProductArray)Msgbox strProductArray(intCount)Next' This will itterate through the array backwardsFor intCount = UBound(strProductArray) To LBound(strProductArray) Step -1Msgbox strProductArray(intCount)Next' To add extra data to an array use Redim PreserveRedim Preserve strProductArray(3)strProductArray(3) = "Mice"' To store the contents of an array into one string, use JoinMsgbox Join(strProductArray, ",")' To delete the contents of an array, use the Erase commandErase strProductArrayDate Manipulation ExamplesSome date manipulation functions.

' show todays dateMsgBox Date

' show the timeMsgBox Time

' show both the date and timeMsgBoxNow

' calculate the minimum Date of Birth for someone who is 18 years oldstrMinDoB = DateAdd("yyyy", -18, Date)MsgBox strMinDob

' show the number of years difference between strMinDob and todayMsgBox DateDiff("yyyy", strMinDob, Date)

MsgBox CompareArrays(sA, sB)' =============================================================' function: CompareArrays' desc : Compares the content of two arrays and checks that' they each contain the same data, even if in a ' different order' params : arrArray1 is the base array' arrArray2 is the array to compare' returns : True if they contain same data, False otherwise' =============================================================Function CompareArrays(arrArray1, arrArray2)

Dim intA1Dim intA2Dim blnMatched

' check that the arrays are the same sizeIf UBound(arrArray1) <> UBound(arrArray2) then

' if the element was not found in array two, return false and exit functionIf Not blnMatched then CompareArrays = FalseExit FunctionEnd If

Next ' next element in first array

' if the function got this far, then the arrays contain the same dataCompareArrays = True

End Function ' CompareArrays

Custom Report EntryCreating a customised entry in the results.

' Example usageCustomReportEntry micFail, "Custom Report Example", "

This is a custom report entry!

"

' =============================================================' function: CustomReportEntry' desc : Creates a customized entry in the result file, you' can use standard HTML tags in the message.' params : strStatus is the result, micPass, micFail etc' strStepName is the name of the step' strMessage is the failure message, this can contain' html tags' returns : Void' =============================================================Function CustomReportEntry(strStatus, strStepName, strMessage)

Bcreating Custom Libraries An example of how to create your own custom library. This example will show you how to create your own customised code library, using Visual Basic 6 as an example.

First thing to do is open Visual Basic and create a new Active X DLL project...

Before we add any code, we should give the Project and the Class Library sensible names.

Here I've called the project "QTP"...

For the Class Library I've simply called it "Library"...

Now we can add a function to our Library. For this example I'm going to use a verybasic function which will simply display a message box with a given parameter value...

Next thing we need to do is create the DLL, this can be done from the File menu in Visual Basic...

Note that during the development of the DLL, you can simply press F5 to run the code in Visual Basic. We can then still call the function from QTP, this allows us to put break-points insidethe Visual Basic code and do some debugging.

Another thing to note is that when you finish the DLL and want to use it on other machines,you will need to register the DLL on the system. This can be done by simply dragging and droppingthe DLL onto the file "RegSvr32.exe", which can be found in your Windows\System32 folder.

Now that we have our new library ready, we can call the functions from QTP...

Execute Method In Regular ExpressionsExecuting a regular expression to find text within a string.

MsgBox RegularExpExample("QTP.", "QTP1 QTP2 qtp3 QTP4")

' =============================================================' function: RegularExpExample' desc : Example of how to use the regular expression object' to find text within a string' params : strPattern is the regular expression' strString is the string to use the expression on' returns : An example string showing the results of the search' =============================================================Function RegularExpExample(strPattern, strString)

Dim objRegEx, strMatch, strMatches Dim strRet

' create regular expression objectSet objRegEx = New RegExp

' set the patternobjRegEx.Pattern = strPattern

' set it be not case sensitiveobjRegEx.IgnoreCase = True

' set global flag so we search all of the string, instead of just searching' for the first occurrenceobjRegEx.Global = True

' =============================================================' function: ReadXLS' desc : Reads a sheet from an XLS file and stores the content' in a multi-dimensional array' params : strFileName is XLS file to read, including path' strSheetName is the name of the sheet to read, i.e "Sheet1"' returns : Multi-dimensional array containing all data from ' the XLS' =============================================================Function ReadXLS(strFileName,strSheetName)

Function FolderDelete(strFolder)Dim objFS' create a file system objectSet objFS = CreateObject("Scripting.FileSystemObject")' check that the source folder existsIf Not objFS.FolderExists(strFolder) Then' fail if the source does not existreporter.ReportEvent micFail, "Delete Folder", "Unable to Delete Folder '"& strFolder &"', It Does Not Exist"Else' delete the folderobjFS.DeleteFolder strFolder

End If' destroy the objectSet objFS = Nothing

End Function 'FolderDeleteMove FolderMove a local or network folder.' =============================================================' function: FolderMove' desc : Moves a folder and all of its files to a new path' params : strSourceFolder - the folder to copy' strDestinationFolder - the location to copy to' returns : void' =============================================================Function FolderMove(strSourceFolder, strDestinationFolder)Dim objFS' create a file system objectSet objFS = CreateObject("Scripting.FileSystemObject")' check that the source folder existsIf Not objFS.FolderExists(strSourceFolder) Then' fail if the source does not existreporter.ReportEvent micFail, "Move Folder", "Source Folder '"& strSourceFolder &"' Does Not Exist"Else' check that the destination folder doesn't already existIf Not objFS.FolderExists(strDestinationFolder) Then

End Function 'FolderMoveCopy FolderCopy a local or network folder.' =============================================================' function: FolderCopy' desc : Copys a folder and all of its files to a new path' params : strSourceFolder - the folder to copy' strDestinationFolder - the location to copy to' returns : void' =============================================================

' =============================================================' function: AppendFile' desc : Writes a line of text to a text file, text file is' created if it doesn't already exist' params : strFileName is the name of the file to write to' strLine is the text to write to the file' returns : void' =============================================================Function AppendFile(strFileName, strLine)

' open each of the files for readingSet objFileA = objFS.OpenTextFile(strFile1, 1)Set objFileB = objFS.OpenTextFile(strFile2, 1)

' repeat the following until we hit the end of one of the filesDo While ((objFileA.AtEndOfStream <> True) OR (objFileB.AtEndOfStream <> True))

' read the next line from both filesstrLineA = objFileA.ReadLinestrLineB = objFileB.ReadLine

' perform a comparison on the line from each fileintCompareResult = StrComp(strLineA,strLineB,0)

' if the value of the comparison is not 0, lines are differentIf (intCompareResult <> 0) Then

' found a difference in the files, so close them bothobjFileA.CloseobjFileB.Close

' destroy the objectSet objFS = Nothing

' return falseCompareFiles = False

' exit the functionExit Function

End If ' if different

Loop ' until end of file

' close both filesobjFileA.CloseobjFileB.Close

' destroy the objectSet objFS = Nothing

' if function got this far, means files are the same, so return TrueCompareFiles = True

End Function 'CompareFiles

Create Desktop ShortcutCreate a shortcut on the desktop.

' =============================================================' function: CreateDesktopShortcut' desc : Creates a shortcut on the desktop' params : strTargetPath is the full path to the file you ' are creating the shortcut to, i.e. c:\doc\me.txt' strLinkName is the name of the shortcut, as it ' appears on the desktop' strDesc is the description to set within the shortcut' returns : void' =============================================================Sub CreateDesktopShortcut(strTargetPath, strLinkName, strDesc)

' set the path within the shortcutobjShortCut.TargetPath = strTargetPath

' set the descriptionobjShortCut.Description = strDesc

' save the shortcutobjShortCut.Save

End Sub ' CreateDesktopShortcut

Read From Excel FileRead all the data from an Excel file.

' =============================================================' function: ReadXLS' desc : Reads a sheet from an XLS file and stores the content' in a multi-dimensional array' params : strFileName is XLS file to read, including path' strSheetName is the name of the sheet to read, i.e "Sheet1"' returns : Multi-dimensional array containing all data from ' the XLS' =============================================================Function ReadXLS(strFileName,strSheetName)

' =============================================================' function: WriteLog' desc : Writes a message to a log file. File is created' inside a Log folder of the current directory' params : strCode is a code to prefix the message with' strMessage is the message to add to the file' returns : void' =============================================================Function WriteLog(strCode, strMessage)

Loop BasicsSome basic information about various loop types.' Loops allow you to run a group of statements repeatidly.'' There are four types of loop available, all very easy to ' use and understand. This code sample will explain how' to use each type of loop.'

' Do...Loop

' The Do...Loop will run a block of statements repeatidly ' while a condition is True, or until a condition becomes True

' Check these two examples of Do...While, there is one major difference ' between them. In Example A the cose will check the value of intCounter' before it enters the loop, but in Example B the code will enter the ' loop regardless of the value of intCounter.

' For...Next Loops will execute a series of statements until a specific counter value ' is reached.For iCounter = 1 To 5MsgBox iCounterNext

' You can add a Step keyword to define how much the counter should increase with each' itteration of the loopFor iCounter = 1 To 10 Step 2MsgBox iCounterNext

' The Step keyword can also be used to itterate backwardsFor iCounter = 5 to 1 Step -1MsgBox iCounterNext

' For...Each

' Another variation on the For...Next loop is the For...Each loop. The For...Each' loop is used to execute a series of statements for each object in a collection, ' i.e. each element of an array. For example...Dim strPeopleListDim strPersonstrPeopleList = Array("Alan", "Bob", "Craig", "Dan")For Each strPerson in strPeopleListMsgBox strPersonNext

' While...Wend Loops'' This type of loop will execute a series of statements as long as ' a given condition is true.' Note: It's advisable to avoid using this type of loop, you should' us the Do...Loop instead' Here's an example anyway...iCounter = 0While iCounter < 5iCounter = iCounter + 1Msgbox iCounterWendMinimize QTPMinimize the main QTP window.

' check that the source file existsIf Not objFS.FileExists(strFile) Then

' fail if the source does not existreporter.ReportEvent micFail, "Move File", "Unable to Move the File '"& strFile &"', It Does Not Exist"

Else

' create the destination folder if it doesn't already existIf Not objFS.FolderExists(strTarget) Then

objFS.CreateFolder(strTarget)

End If

' move the fileobjFS.MoveFile strFile, strTarget

End If

' destroy the objectSet objFS = Nothing

End Function 'FileMoveMove FolderMove a local or network folder.' =============================================================' function: FolderMove' desc : Moves a folder and all of its files to a new path' params : strSourceFolder - the folder to copy' strDestinationFolder - the location to copy to' returns : void' =============================================================Function FolderMove(strSourceFolder, strDestinationFolder)Dim objFS' create a file system objectSet objFS = CreateObject("Scripting.FileSystemObject")' check that the source folder existsIf Not objFS.FolderExists(strSourceFolder) Then' fail if the source does not existreporter.ReportEvent micFail, "Move Folder", "Source Folder '"& strSourceFolder &"' Does Not Exist"Else' check that the destination folder doesn't already existIf Not objFS.FolderExists(strDestinationFolder) Then

End Function 'FolderMoveDisplaying Dialog BoxesHow to display and use various types of dialog box.' display a basic message boxMsgBox "Hi, this is a message box", vbOkOnly, "Message Title"

' prompt the user with a questionstrAnswer = InputBox("Hi, how are you today?","Question")' show the user what they just typedMsgBox "You are - " & strAnswer

' ask the user to select an optionstrAnswer = MsgBox("Do you want to proceed?", vbYesNo, "Question")' show the user what they just selectedIf strAnswer = vbNo ThenMsgBox "You selected No"ElseMsgBox "You selected Yes"End IfNote: Here are the various message types you can play with...vbOKOnlyvbOKCancelvbAbortRetryIgnorevbYesNoCancelvbYesNovbRetryCancelvbCriticalvbQuestionvbExclamationvbInformation

Using Programmatic DescriptionsUsing Programmatic Descriptions to interact with a web page.This example will illustrate how to use programmatic descriptions to interact with a web page, www.QTPHelper.com to be more exact...Note that I've used a simple regular expression in the Browser and Page description, just in case the titles change in the future.' click the Home linkBrowser("Title:=QTP Helper.*").Page("Title:=QTP Helper.*").Link("Text:=Home").Click

' =============================================================' function: ReadXLS' desc : Reads a sheet from an XLS file and stores the content' in a multi-dimensional array' params : strFileName is XLS file to read, including path' strSheetName is the name of the sheet to read, i.e "Sheet1"' returns : Multi-dimensional array containing all data from ' the XLS' =============================================================Function ReadXLS(strFileName,strSheetName)

' =============================================================' function: CustomReportEntry' desc : Creates a customized entry in the result file, you' can use standard HTML tags in the message.' params : strStatus is the result, micPass, micFail etc' strStepName is the name of the step' strMessage is the failure message, this can contain' html tags' returns : Void' =============================================================Function CustomReportEntry(strStatus, strStepName, strMessage)

' =============================================================' function: WriteLog' desc : Writes a message to a log file. File is created' inside a Log folder of the current directory' params : strCode is a code to prefix the message with' strMessage is the message to add to the file' returns : void' =============================================================Function WriteLog(strCode, strMessage)

End Function ' WriteLogCheck Service is RunningCheck to see if a windows service is running.

' =============================================================' function: CheckIfServiceIsRunning' desc : Check to see if a service is running' params : strServiceName is the name of the service' returns : True if running, False otherwise' =============================================================Function CheckIfServiceIsRunning(strServiceName)

Using Description ObjectsUsing Description Objects to interact with a web page.This example will illustrate how to use description objects to interact with a web page, www.QTPHelper.com to be more exact...Note that for the Browser and Page I've used programmatic descriptions, but for the buttons, edits and check-boxes I've used Description Objects. Also take note of the regular expression in the Browser and Page description, just in case the titles change in the future.You can add more properties to your description objects if you need to, i.e. if your web page has numerous objects of the same type with similar property values. Dim objLogoutDim objUserDim objPassDim objRemember

Using Programmatic DescriptionsUsing Programmatic Descriptions to interact with a web page.This example will illustrate how to use programmatic descriptions to interact with a web page, www.QTPHelper.com to be more exact...Note that I've used a simple regular expression in the Browser and Page description, just in case the titles change in the future.' click the Home linkBrowser("Title:=QTP Helper.*").Page("Title:=QTP Helper.*").Link("Text:=Home").Click

What is QuickTest Automation Object Model?It's a way to write scripts so as to automate your QuickTest operations.

Some places where we can use AOMThis is a small list of places (but not limited to) where we can use AOM. Thumb Rule - Use it at any place where you find yourself doing repetitive tasks while using QTP. • AOM can come handy when you have a large no of scripts to be uploaded to QC. A simple script can save you hours of manual work! • Use AOM to initialize QTP options and settings like add-ins etc. • You can use AOM to call QTP from other application: For ex: You can write a macro for calling QTP from excel. Caution: AOM should be used outside of QTP and not within the script (during playback). Though there is no harm using it inside but some of the AOM statements might fail.

How to write AOM scripts?You need to understand that the very root of QT AOM is Application Object. Every automation script begins with the creation of the QuickTest "Application" object. Creating this object does not start QuickTest. It simply provides an object from which you can access all other objects, methods and properties of the QuickTest automation object model.You can create only one instance of the Application object. You do not need to recreate the QuickTest Application object even if you start and exit QuickTest several times during your script. Once you have defined this object you can then successfully work and perform operations on other objects given in Quick Test Pro > Documentation > QuickTest Automation Reference.For ex: Let us connect to TD QC using AOM and open a script "qtp_demo"Dim qt_obj 'Define a Quick Test object qt_obj = CreateObject("Quick Test.Application") ' Instantiate a QT Object. It does not start QTP.qt_obj.launch ' Launch QT qt_obj.visible ' Make QT visible qt_obj.TDConnection.Connect "http://tdserver/tdbin", _ 'Referencing TDConnection Object "TEST_DOMAIN", "TEST_Project", "Ankur", "Testing", False ' Connect to Quality Center If qt_obj.TDConnection.IsConnected Then ' If connection is successful qt_obj.Open "[QualityCenter] Subject\tests\qtp_demo", False ' Open the test Else MsgBox "Cannot connect to Quality Center" ' If connection is not successful, display an error message. End IfTo quickly generate an AOM script with the current QTP settings. Use the Properties tab of the Test Settings dialog box (File > Settings) OR the General tab of the Options dialog box (Tools > Options) OR the Object Identification dialog box (Tools > Object Identification). Each contain a "Generate Script" button. Clicking this button generates a automation script file (.vbs) containing the current settings from the corresponding dialog box. You can run the generated script as is to open QuickTest with the exact configuration of the QuickTest application that generated the script, or you can copy and paste selected lines from the generated files into your own automation script. Reference: Quick Test Pro > Documentation > QuickTest Automation Reference.

What is QuickTest Automation Object Model?It's a way to write scripts so as to automate your QuickTest operations.

Some places where we can use AOMThis is a small list of places (but not limited to) where we can use AOM. Thumb Rule - Use it at any place where you find yourself doing repetitive tasks while using QTP. • AOM can come handy when you have a large no of scripts to be uploaded to QC. A simple script can save you hours of manual work! • Use AOM to initialize QTP options and settings like add-ins etc. • You can use AOM to call QTP from other application: For ex: You can write a macro for calling QTP from excel. Caution: AOM should be used outside of QTP and not within the script (during playback). Though there is no harm using it inside but some of the AOM statements might fail.

How to write AOM scripts?You need to understand that the very root of QT AOM is Application Object. Every automation script begins with the creation of the QuickTest "Application" object. Creating this object does not start QuickTest. It simply provides an object from which you can access all other objects, methods and properties of the QuickTest automation object model.You can create only one instance of the Application object. You do not need to recreate the QuickTest Application object even if you start and exit QuickTest several times during your script. Once you have defined this object you can then successfully work and perform operations on other objects given in Quick Test Pro > Documentation > QuickTest Automation Reference.For ex: Let us connect to TD QC using AOM and open a script "qtp_demo"Dim qt_obj 'Define a Quick Test object qt_obj = CreateObject("Quick Test.Application") ' Instantiate a QT Object. It does not start QTP.qt_obj.launch ' Launch QT qt_obj.visible ' Make QT visible qt_obj.TDConnection.Connect "http://tdserver/tdbin", _ 'Referencing TDConnection Object "TEST_DOMAIN", "TEST_Project", "Ankur", "Testing", False ' Connect to Quality Center If qt_obj.TDConnection.IsConnected Then ' If connection is successful qt_obj.Open "[QualityCenter] Subject\tests\qtp_demo", False ' Open the test Else MsgBox "Cannot connect to Quality Center" ' If connection is not successful, display an error message. End IfTo quickly generate an AOM script with the current QTP settings. Use the Properties tab of the Test Settings dialog box (File > Settings) OR the General tab of the Options dialog box (Tools > Options) OR the Object Identification dialog box (Tools > Object Identification). Each contain a "Generate Script" button. Clicking this button generates a automation script file (.vbs) containing the current settings from the corresponding dialog box. You can run the generated script as is to open QuickTest with the exact configuration of the QuickTest application that generated the script, or you can copy and paste selected lines from the generated files into your own automation script. Reference: Quick Test Pro > Documentation > QuickTest Automation Reference.