There might be cases where you want to enter the same value in all the objects of the same class like an edit box. This is particularly useful when checking for field level validations. The approach to be followed can be to identify all the childobjects in the page belonging to the same class, and then trying to set the value or retrieve a value. The below piece of code can be used to enter the same text in all the WebEdit objects in the YahooMail page.
Set objIE = CreateObject("InternetExplorer.Application")
objIE.Visible = True
objIE.Navigate "www.yahoomail.com"
Browser("Google").Page("Yahoo! Mail: The best").Sync
Set objDesc = Description.Create
objDesc("micclass").Value = "WebEdit"
Set Child = Browser("Google").Page("Yahoo! Mail: The best").ChildObjects(objDesc)
For iCount = 0 to Child.count -1
Child(iCount).Highlight
Child(iCount).Set "Divya Rakesh"
Next
Search This Blog
Wednesday, December 1, 2010
Associating all the library files from a folder before start
Using the below code you can add all the library files in folder from a vbs script at the beginning of the session. This same vbs file can be used for doing all the settings as well, like opening QTP, opening the test, associating all resources and then running the test. You can easily get the script by modifying the script that is generated when the user gives Generate script in the File Settings. The below part of the code can be updated to this vbs file to associate all the library file from a given folder.
Set objFile = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFile.GetFolder("E:\Automation\Library")
Set objFiles = objFolder.Files
For each sFile in objFiles
sExtn = Right (sFile, 3)
If sExtn = "vbs" or sExtn = "qfl" Then
App.Test.Settings.Resources.Libraries.Add sFile
End If
Next
Set objFile = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFile.GetFolder("E:\Automation\Library")
Set objFiles = objFolder.Files
For each sFile in objFiles
sExtn = Right (sFile, 3)
If sExtn = "vbs" or sExtn = "qfl" Then
App.Test.Settings.Resources.Libraries.Add sFile
End If
Next
Wednesday, October 27, 2010
Lock your machine through the script
Add the below code to end of script to lock the machine automatically
Set obj = CreateObject("WScript.Shell")
sCmnd = "%windir%\SYSTEM32\rundll32.exe user32.dll,LockWorkStation"
obj.Run sCmnd, 0, False
Set obj =nothing
Set obj = CreateObject("WScript.Shell")
sCmnd = "%windir%\SYSTEM32\rundll32.exe user32.dll,LockWorkStation"
obj.Run sCmnd, 0, False
Set obj =nothing
Tuesday, October 19, 2010
Getting the Machine Name through the Script
The below piece of code will give you the machine name and the user name of the pc where it is running. This is particularly useful when we need system parameters:
Set oWshNetwork = CreateObject("WScript.Network")
sMachine = oWshNetwork.ComputerName
sUser = oWshNetwork.UserName
msgbox sMachine
msgbox sUser
You can get all other system params also using similar codes using WScript.Network
Set oWshNetwork = CreateObject("WScript.Network")
sMachine = oWshNetwork.ComputerName
sUser = oWshNetwork.UserName
msgbox sMachine
msgbox sUser
You can get all other system params also using similar codes using WScript.Network
Thursday, October 14, 2010
Memory Usage Using WMI
The below code can be used to get the memory usage, peak memory usage and the virtual memory usage as in the Task Manager without opening it. Here we are using the WMI object methods:
' To get the Machine Name
Set objWMISvc = GetObject( "winmgmts:\\.\root\cimv2" )
Set colItems = objWMISvc.ExecQuery( "Select * from Win32_ComputerSystem", , 48 )
For Each objItem in colItems
PCName = objItem.Name
Next
'To get the Memory Values
On Error Resume Next
arrComputers = Array(PCName)
For Each strComputer In arrComputers
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_Process")
For Each objItem In colItems
If objItem.Name = "ProcessNameYouWant.exe" Then
VM = objItem.PageFileUsage/1024
End If
Next
Set MemItems = objWMIService.ExecQuery("SELECT * FROM Win32_PerfFormattedData_PerfProc_Process", "WQL", _
wbemFlagReturnImmediately + wbemFlagForwardOnly)
For Each objItem In MemItems
If objItem.Name = "ProcessNameYouWant" Then
mem = objItem.WorkingSet/1024
peak = objItem.WorkingSetPeak/1024
End If
Next
Next
' To get the Machine Name
Set objWMISvc = GetObject( "winmgmts:\\.\root\cimv2" )
Set colItems = objWMISvc.ExecQuery( "Select * from Win32_ComputerSystem", , 48 )
For Each objItem in colItems
PCName = objItem.Name
Next
'To get the Memory Values
On Error Resume Next
arrComputers = Array(PCName)
For Each strComputer In arrComputers
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_Process")
For Each objItem In colItems
If objItem.Name = "ProcessNameYouWant.exe" Then
VM = objItem.PageFileUsage/1024
End If
Next
Set MemItems = objWMIService.ExecQuery("SELECT * FROM Win32_PerfFormattedData_PerfProc_Process", "WQL", _
wbemFlagReturnImmediately + wbemFlagForwardOnly)
For Each objItem In MemItems
If objItem.Name = "ProcessNameYouWant" Then
mem = objItem.WorkingSet/1024
peak = objItem.WorkingSetPeak/1024
End If
Next
Next
Wednesday, October 13, 2010
Add or Remove the Recovery Scenario dynamically from tge script
The below code is helpful in adding and removing the Recovery Scenario dynamically from the settings. This case would be particularly required in case where there is a looping of the recovery scenarios, i.e, a recovery scenario is triggered when inside another recovery scenario.
Here goes the code:
Set qtApp = CreateObject("QuickTest.Application")
Set qtTestRecovery = qtApp.Test.Settings.Recovery
'This part of the code is used to remove all the existing recovery scenarios associated with the test
If qtTestRecovery.Count > 0 Then
qtTestRecovery.RemoveAll
End If
' This is used to add the recovery scenarios. The first parameter is the location of the qrs file. 2nd parameter is the scenario name as given at the time of creating the recovery scenario and 3rd is the priority (used when multiplr scenarios need to be added. At that time we can have 1,2,3 etc)
qtTestRecovery.Add "E:\RecoveryScenario.qrs", "RecoveryScenario" , 1
For intIndex = 1 To qtTestRecovery.Count
qtTestRecovery.Item(intIndex).Enabled = True
Next
qtTestRecovery.Enabled = true
qtTestRecovery.SetActivationMode "OnError"
Set qtApp = Nothing
Set qtTestRecovery = Nothing
'Only if the below line of code is added the recovery scenario would be added to your code.
Recovery.Enabled= True
Here goes the code:
Set qtApp = CreateObject("QuickTest.Application")
Set qtTestRecovery = qtApp.Test.Settings.Recovery
'This part of the code is used to remove all the existing recovery scenarios associated with the test
If qtTestRecovery.Count > 0 Then
qtTestRecovery.RemoveAll
End If
' This is used to add the recovery scenarios. The first parameter is the location of the qrs file. 2nd parameter is the scenario name as given at the time of creating the recovery scenario and 3rd is the priority (used when multiplr scenarios need to be added. At that time we can have 1,2,3 etc)
qtTestRecovery.Add "E:\RecoveryScenario.qrs", "RecoveryScenario" , 1
For intIndex = 1 To qtTestRecovery.Count
qtTestRecovery.Item(intIndex).Enabled = True
Next
qtTestRecovery.Enabled = true
qtTestRecovery.SetActivationMode "OnError"
Set qtApp = Nothing
Set qtTestRecovery = Nothing
'Only if the below line of code is added the recovery scenario would be added to your code.
Recovery.Enabled= True
Tuesday, September 21, 2010
Recovery Scenario for Unknown Window
The following code can be added in the recovery scenario as a function call. When the occurence is set to "On Error" it will check for any unknown window, if it finds this unknown window, it will click ok or cancel button or any other button which we are giving in the script. If there is not such unwindow and still the object expected by QTP is not visible, then it will also click Retry for the QTP error.
This is very important since we are handling here both application generated as well as QTP generated errors. You can also add the function for caputuring the screenshot here to make it an excellent looking Recovery Scenario.
Function UnknownWindow(Object, Method, Arguments, retVal)
Dim var
var=Array("&No","OK","Ok", "Cancel", "Close")
Set o_Desc=description.Create
Set o_Nobutn=description.Create
o_Desc("Class Name").value="Dialog"
o_Desc("ispopupwindow").value=True
If Window(o_Desc).Exist Then
Window(o_Desc).Activate
Arr_Count=Ubound(var)
For i= 0 to Arr_Count
o_Nobutn("text").value=var(i)
If Window(o_Desc).winbutton(o_Nobutn).Exist(0) Then
Enabled = Window(o_Desc).winbutton(o_Nobutn).GetROProperty("enabled")
If Enabled = "True" Then
Exit For
End If
End If
Next
Window(o_Desc).winbutton(o_Nobutn).Click
Else
QTP_Error
End If
End Function
'-----------------------------------------------------------
Public Function QTP_Error
count = 1
For Count = 1 to 2
Set WshShell =CreateObject("WScript.Shell")
Btncode = WshShell.Popup ("object is disabled", 1)
WshShell.SendKeys "{TAB}"
wait 2
WshShell.SendKeys "~"
Next
CloseApplication
ExitTestIteration
End Function
This is very important since we are handling here both application generated as well as QTP generated errors. You can also add the function for caputuring the screenshot here to make it an excellent looking Recovery Scenario.
Function UnknownWindow(Object, Method, Arguments, retVal)
Dim var
var=Array("&No","OK","Ok", "Cancel", "Close")
Set o_Desc=description.Create
Set o_Nobutn=description.Create
o_Desc("Class Name").value="Dialog"
o_Desc("ispopupwindow").value=True
If Window(o_Desc).Exist Then
Window(o_Desc).Activate
Arr_Count=Ubound(var)
For i= 0 to Arr_Count
o_Nobutn("text").value=var(i)
If Window(o_Desc).winbutton(o_Nobutn).Exist(0) Then
Enabled = Window(o_Desc).winbutton(o_Nobutn).GetROProperty("enabled")
If Enabled = "True" Then
Exit For
End If
End If
Next
Window(o_Desc).winbutton(o_Nobutn).Click
Else
QTP_Error
End If
End Function
'-----------------------------------------------------------
Public Function QTP_Error
count = 1
For Count = 1 to 2
Set WshShell =CreateObject("WScript.Shell")
Btncode = WshShell.Popup ("object is disabled", 1)
WshShell.SendKeys "{TAB}"
wait 2
WshShell.SendKeys "~"
Next
CloseApplication
ExitTestIteration
End Function
Capturing the screenshot in case of error
The following piece of code can be inserted as a fucntion call in you recovery scenario. If you set the occurence as "On Error", it will take the screenshot of your screen in the event of an error. This is helpful in understanding what exactly happend before the recovery scenario was triggered.
Dim filename
Set FSO = CreateObject("Scripting.FileSystemObject")
If FSO.FolderExists("D:\Automation\Results\Screenshots")= "False" Then
FSO.CreateFolder("D:\Automation\Results\Screenshots")
End If
timenow = now
timenw= split (timenow, " ")
filename = RecipeNo &"_"&timenw(1)&".png"
filename = Replace(filename,"/","")
filename = Replace(filename,":","")
filename = "D:\Ranger Automation\Results\Screenshots"&"\"&filename
Desktop.CaptureBitmap filename,true
Reporter.ReportEvent micFail,"image","<"
Dim filename
Set FSO = CreateObject("Scripting.FileSystemObject")
If FSO.FolderExists("D:\Automation\Results\Screenshots")= "False" Then
FSO.CreateFolder("D:\Automation\Results\Screenshots")
End If
timenow = now
timenw= split (timenow, " ")
filename = RecipeNo &"_"&timenw(1)&".png"
filename = Replace(filename,"/","")
filename = Replace(filename,":","")
filename = "D:\Ranger Automation\Results\Screenshots"&"\"&filename
Desktop.CaptureBitmap filename,true
Reporter.ReportEvent micFail,"image","<"
Create a line chart in excel
Set Excel = CreateObject("Excel.Application")
Set Book = Excel.Workbooks.Open("E:\Performance.xls")
Set Sheet = Book.Worksheets(1)
Set Range = Sheet.UsedRange
Range.Select ' Selects the area in the excel sheet with the data
Set Charts= Excel.Charts
Charts.Add
Set objCharts = Charts(1)
objCharts.Activate
objCharts.ChartType = 65 ' This will select a line chart
objCharts.SeriesCollection(1).Border.Weight = -4138 'Used to increase the width of the line in the graph
objCharts.SeriesCollection(2).Border.Weight = -4138
objCharts.SeriesCollection(3).Border.Weight = -4138
Book.Save
Excel.Quit
For more details and other types of charts. Please refer the website:
http://technet.microsoft.com/en-us/library/ee692900.aspx
Set Book = Excel.Workbooks.Open("E:\Performance.xls")
Set Sheet = Book.Worksheets(1)
Set Range = Sheet.UsedRange
Range.Select ' Selects the area in the excel sheet with the data
Set Charts= Excel.Charts
Charts.Add
Set objCharts = Charts(1)
objCharts.Activate
objCharts.ChartType = 65 ' This will select a line chart
objCharts.SeriesCollection(1).Border.Weight = -4138 'Used to increase the width of the line in the graph
objCharts.SeriesCollection(2).Border.Weight = -4138
objCharts.SeriesCollection(3).Border.Weight = -4138
Book.Save
Excel.Quit
For more details and other types of charts. Please refer the website:
http://technet.microsoft.com/en-us/library/ee692900.aspx
Monday, August 30, 2010
Creating, Renaming and Data Entry in Excel
The below code is for creating your own excel application, custom naming the sheets and entering data in an excel. This is very useful if you have to get some data from the application and your datatable already has some other application input data. Basically a case where you need to have more than one excel sheets.
Set Excel = CreateObject("Excel.Application")
Set Book = Excel.Workbooks.Add
Set Sheet = Book.Worksheets(1)
Sheet.Name = "Results"
Sheet.Rows(1).Columns(1).value = "This is the first Sheet"
Book.SaveAs "D:\Results.xls"
Book.Close
Excel.Quit
To Rename the second sheet you just need to modify the Worksheet id in the above code. It would look like
Set Excel = CreateObject("Excel.Application")
Set Book = Excel.Workbooks.Open ("D:\Results.xls")
Set Sheet1 = Book.Worksheets(2)
Sheet1.Name = "Output_Data"
You need not close the excel to rename the second sheet. This code can be combined with the above code also. As per your needs. But you should make sure that the name does not exceed the default length in excel
Set Excel = CreateObject("Excel.Application")
Set Book = Excel.Workbooks.Add
Set Sheet = Book.Worksheets(1)
Sheet.Name = "Results"
Sheet.Rows(1).Columns(1).value = "This is the first Sheet"
Book.SaveAs "D:\Results.xls"
Book.Close
Excel.Quit
To Rename the second sheet you just need to modify the Worksheet id in the above code. It would look like
Set Excel = CreateObject("Excel.Application")
Set Book = Excel.Workbooks.Open ("D:\Results.xls")
Set Sheet1 = Book.Worksheets(2)
Sheet1.Name = "Output_Data"
You need not close the excel to rename the second sheet. This code can be combined with the above code also. As per your needs. But you should make sure that the name does not exceed the default length in excel
Friday, August 27, 2010
Sending mails using Outlook and SMTP
Here we will see how we can send the mail after the test run using outlook and also using SMTP. First let us see how to send the mail using Outlook. This method though useful has the following drawbacks:
1. The system or machine where you are running the scripts should have outlook configured in it
2. The email will be sent in the name of the person whose email has been configured in the outlook.
3. Finally, outlook throws up a security message when you try to send an automated mail and to take care of this you will have to download a third party software called expressclick.
Well, if you still prefer to go by this method, then here is the code
systemutil.Run "C:\Program Files\Express ClickYes\ClickYes.exe"
wait 5
set oMailobj=CreateObject("Outlook.Application")
set oSendmail=oMailobj.CreateItem(0)
oSendmail.To=""
'oSendmail.Cc=""
oSendmail.Subject="Test"
oSendmail.Body="Hi" & vbcrLf & vbCrlf & "PFA the Smoke Test Automation Results" & vbCrlf & vbCrlf & "Thanks" & vbcrlf & "Automation Team"
sAttachment = "D:\Results.zip"
If (sAttachment <> "") Then
oSendmail.Attachments.Add(sAttachment)
Else
Reporter.ReportEvent micInfo,"Sending mail:","Unable to send attachment,please verify your attachment file"
End If
oSendmail.Send
wait 3
set oSendmail=Nothing
set oMailobj=Nothing
SystemUtil.CloseProcessByName "ClickYes.exe"
All these problems can be overcome by using SMTP mail. The only thing that you need to know is the SMTP server name and the machine should be in the network. Once you use this code you will never go back to using Outlook.
Set oMessage = CreateObject("CDO.Message")
oMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
'SMTP Server
oMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserver") ="servername or ip"
oMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
oMessage.Configuration.Fields.Update
oMessage.Subject = "Test"
oMessage.Sender = "" ' any non-existing mail id will also work.
oMessage.To =""
'oMessage.CC = ""
'oMessage.BCC = ""
oMessage.AddAttachment "D:\Results.zip"
oMessage.TextBody = "Hi" & vbcrLf & vbCrlf & "PFA the Smoke Test Automation Results & vbCrlf & vbCrlf & "Thanks" & vbcrlf & "Automation Team" & vbCrlf & vbCrlf & vbCrlf &"*********************************************************************************************************" & vbcrlf & "This is an auto-generated email. Please do not reply to this email." & vbcrlf &"*********************************************************************************************************"
oMessage.Send
Set oMessage = Nothing
1. The system or machine where you are running the scripts should have outlook configured in it
2. The email will be sent in the name of the person whose email has been configured in the outlook.
3. Finally, outlook throws up a security message when you try to send an automated mail and to take care of this you will have to download a third party software called expressclick.
Well, if you still prefer to go by this method, then here is the code
systemutil.Run "C:\Program Files\Express ClickYes\ClickYes.exe"
wait 5
set oMailobj=CreateObject("Outlook.Application")
set oSendmail=oMailobj.CreateItem(0)
oSendmail.To="
'oSendmail.Cc="
oSendmail.Subject="Test"
oSendmail.Body="Hi" & vbcrLf & vbCrlf & "PFA the Smoke Test Automation Results" & vbCrlf & vbCrlf & "Thanks" & vbcrlf & "Automation Team"
sAttachment = "D:\Results.zip"
If (sAttachment <> "") Then
oSendmail.Attachments.Add(sAttachment)
Else
Reporter.ReportEvent micInfo,"Sending mail:","Unable to send attachment,please verify your attachment file"
End If
oSendmail.Send
wait 3
set oSendmail=Nothing
set oMailobj=Nothing
SystemUtil.CloseProcessByName "ClickYes.exe"
All these problems can be overcome by using SMTP mail. The only thing that you need to know is the SMTP server name and the machine should be in the network. Once you use this code you will never go back to using Outlook.
Set oMessage = CreateObject("CDO.Message")
oMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
'SMTP Server
oMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserver") ="servername or ip"
oMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
oMessage.Configuration.Fields.Update
oMessage.Subject = "Test"
oMessage.Sender = "
oMessage.To ="
'oMessage.CC = "
'oMessage.BCC = "
oMessage.AddAttachment "D:\Results.zip"
oMessage.TextBody = "Hi" & vbcrLf & vbCrlf & "PFA the Smoke Test Automation Results & vbCrlf & vbCrlf & "Thanks" & vbcrlf & "Automation Team" & vbCrlf & vbCrlf & vbCrlf &"*********************************************************************************************************" & vbcrlf & "This is an auto-generated email. Please do not reply to this email." & vbcrlf &"*********************************************************************************************************"
oMessage.Send
Set oMessage = Nothing
Tuesday, August 17, 2010
How to close an application opened through QTP
For opening an application through QTP we use the command SystemUtil.Run. We have a similar command for closing the opened function we as well. Both opening and closing an application called "application" is illustrated below:
Opening an application through QTP:
SystemUtil.Run "C:\Program Files\Application.exe", " ", "C:\Program Files", " "
Closing the same applcation through QTP:
SystemUtil.CloseProcessByName "Application.exe"
Other similar commands available are mentioned below and their names are self explainatory.
SystemUtil.CloseDescendentProcesses
SystemUtil.CloseProcessByHwnd
SystemUtil.CloseProcessById
SystemUtil.CloseProcessByWndTitle
Opening an application through QTP:
SystemUtil.Run "C:\Program Files\Application.exe", " ", "C:\Program Files", " "
Closing the same applcation through QTP:
SystemUtil.CloseProcessByName "Application.exe"
Other similar commands available are mentioned below and their names are self explainatory.
SystemUtil.CloseDescendentProcesses
SystemUtil.CloseProcessByHwnd
SystemUtil.CloseProcessById
SystemUtil.CloseProcessByWndTitle
Monday, August 16, 2010
How to search for data in a tab separated log file
Set Fso = CreateObject("Scripting.FileSystemObject")
Const ForReading = 1, ForWriting = 2
Set File1 = Fso.OpenTextFile ("abc.txt", ForReading, True)
Do While File1.AtEndOfStream <> True
text = File1.ReadLine()
newtext = replace (text, " ", " ")' Copy the tab from the Notepad and paste here.For details check the syntax for Replace function in QTP help
data = split (newtext, " ")
For i = Lbound(data) to UBound(data)
If data(i) = "TimeStamp" Then
msgbox "true"
End If
Next
Loop
Const ForReading = 1, ForWriting = 2
Set File1 = Fso.OpenTextFile ("abc.txt", ForReading, True)
Do While File1.AtEndOfStream <> True
text = File1.ReadLine()
newtext = replace (text, " ", " ")' Copy the tab from the Notepad and paste here.For details check the syntax for Replace function in QTP help
data = split (newtext, " ")
For i = Lbound(data) to UBound(data)
If data(i) = "TimeStamp" Then
msgbox "true"
End If
Next
Loop
Monday, August 9, 2010
Getting the data from a WinList View Object
The below code explains how we can extract the data from a WinListView object and store that data in the run time DataTable and also export it to the required location in the end.
Col_count = Window(" ").WinlistView(" ").ColumnCount
Row_count = Window(" ").WinlistView(" ").GetROProperty("items count")
For i = 0 to Col_count
Col_Header = Window(" ").WinlistView(" ").GetColumnHeader(i)
DataTable.GetSheet(1).AddParameter(Col_Header, "") ' This is to add the column header to the datatable
Next
For i = 0 to Row_count
DataTable.SetCurrentRow(i+1)
For j = 0 to Col_count
Header = Window(" ").WinlistView(" ").GetColumnHeader(j)
Row_Item = Window(" ").WinlistView(" ").GetItem(i)
Var = Window(" ").WinlistView(" ").GetSubItem (Row_Item, Header)
DataTable(Header, GlobalDt)= Var
Next
Next
DataTable.Export "C:\QTP Automation\WinlistView_Data.xls"
Col_count = Window(" ").WinlistView(" ").ColumnCount
Row_count = Window(" ").WinlistView(" ").GetROProperty("items count")
For i = 0 to Col_count
Col_Header = Window(" ").WinlistView(" ").GetColumnHeader(i)
DataTable.GetSheet(1).AddParameter(Col_Header, "") ' This is to add the column header to the datatable
Next
For i = 0 to Row_count
DataTable.SetCurrentRow(i+1)
For j = 0 to Col_count
Header = Window(" ").WinlistView(" ").GetColumnHeader(j)
Row_Item = Window(" ").WinlistView(" ").GetItem(i)
Var = Window(" ").WinlistView(" ").GetSubItem (Row_Item, Header)
DataTable(Header, GlobalDt)= Var
Next
Next
DataTable.Export "C:\QTP Automation\WinlistView_Data.xls"
Friday, July 30, 2010
Object Not Recognized
What can be done if the Objects are not being recognised as expected by QTP
1. Make sure you have the appropriate add ins installed
2. Try opening QTP first and then the application and also visa-versa
3. Try opening the application through QTP by changing the Record and Run settings. Add the url for the application and then select the option "Record and Run only on"
4. Try opening the application through SytemUtil.Run and then try
5. Check the object type with the developers are try to decide which property an be used to uniquely identify the object
6. Go for descriptive programming
7. Try and create Virtual objects and try
8. Go for some misc options to find a work around like active cursor, active tab. Also try if it is possible to get to the object using the keyboard shortcuts.
9. Last but not the least check if there is some work around with out touching that part of the page or screen. This is generally not prefered at all.
1. Make sure you have the appropriate add ins installed
2. Try opening QTP first and then the application and also visa-versa
3. Try opening the application through QTP by changing the Record and Run settings. Add the url for the application and then select the option "Record and Run only on"
4. Try opening the application through SytemUtil.Run and then try
5. Check the object type with the developers are try to decide which property an be used to uniquely identify the object
6. Go for descriptive programming
7. Try and create Virtual objects and try
8. Go for some misc options to find a work around like active cursor, active tab. Also try if it is possible to get to the object using the keyboard shortcuts.
9. Last but not the least check if there is some work around with out touching that part of the page or screen. This is generally not prefered at all.
Creating Objects
To create user defined objects and give them properties that you want
Myobj = Description.Create()
Myobj("Attachedtext").Value = "Agent"
Myobj("htmltag").Value = "A"
The object is now created. Now let us see how we can use this object in our script
Dialog(" ").WinEdit(Myobject).Set "Name"
Myobj = Description.Create()
Myobj("Attachedtext").Value = "Agent"
Myobj("htmltag").Value = "A"
The object is now created. Now let us see how we can use this object in our script
Dialog(" ").WinEdit(Myobject).Set "Name"
Basic Excel
Lets us open an excel sheet and try to read and write data into it.
Set Excel = CreateObject("Excel.Application")
Set Book = Excel.Workbooks.Open("Path")
Set Sheet = Book.Worksheets("Global")
For Row = 1 to 4
For Col = 1 to 3
msgbox Sheet.Rows(Row).Columns(Col)
Next
Next
For Row = 1 to 4
For Col = 1 to 3
Sheet.Rows(Row).Columns(Col).value = Row+Col
Next
Next
Set Excel = CreateObject("Excel.Application")
Set Book = Excel.Workbooks.Open("Path")
Set Sheet = Book.Worksheets("Global")
For Row = 1 to 4
For Col = 1 to 3
msgbox Sheet.Rows(Row).Columns(Col)
Next
Next
For Row = 1 to 4
For Col = 1 to 3
Sheet.Rows(Row).Columns(Col).value = Row+Col
Next
Next
Calculator Automation
In this we are trying to automate the basic fucntions of the Calculator i.e Addition, Subtraction, Multiplication and Division. We are doing this here for 25 rows of data. After each iteration the results are being compared with another excel sheet that has the results already calculated. This is for the purpose of verfication. We are also capturing the memory usage for the Calculaotr Application in the process. The code is divided into 2 segments: one is the main where we have only the function calls and the second is the functions space where we store all our functions as .vbs files.
Main
Open_Calculator
Check_Launch
Load_Data
Check_RowCount
Add_Parameter
For Set_Row= 1 to 10
If Set_Row = 1or Set_Row = 7 or Set_Row = 14 or Set_Row = 20 or Set_Row = 25 Then
Task_Manager()
End If
Environment.Value("Incorrect_Input")=0
Call_Arithemetic (Set_Row)
Next
File_Name=InputBox("Enter the file name f or the Results file")
SaveClose(File_Name)
Functions
********* Application Launch Checkpoint ***********************
Public Function Check_Launch()
Wait 2
If Window("Calculator").Exist Then
Reporter.ReportEvent micPass, "Application Launch", "The application has launched successfully"
Else
Reporter.ReportEvent micFail, "Application Launch", "The application has failed to launch"
End If
End Function
'******** Check Row Count ****************************
Public Function Check_RowCount()
RowCount = DataTable.GetRowCount
If RowCount=25 Then
Reporter.ReportEvent micPass, "RowCount", "There are 25 rows of data"
Else
Reporter.ReportEvent micFail, "RowCount", "Incorrect Row Count. It should be 25 instead of "&RowCount
End If
End Function
'******* Check the typed data *************
Public Function Check_TypedData(Num)
Text= Window("Calculator").WinEdit("Input_Output Box").GetROProperty("text")
Text=clng (Text)
Text=RTrim(Text)
Text=LTrim(Text)
If Text = Num Then
Reporter.ReportEvent micPass, "TypedText", "The typed data is the same as in the input file"
Else
Reporter.ReportEvent micFail, "TypedText", "The typed data does not match the data in the input file"
Environment.Value ("Incorrect_Input") = 1
DataTable("Status", Globaldt)= "Fail"
DataTable("Description", Globaldt) = "Entered number " & Num & " and Calculator output " & Text & " do not match"
End If
End Function
'*********************** Check the Output Data *****************
Public Function Perform_Operation (k, Numbers, Operation)
If Environment.Value ("Incorrect_Input") = 0 Then
If Numbers=3 Then
Get_Digits(DataTable(k,Globaldt))
Check_TypedData (DataTable(k,Globaldt))
Else
Get_Digits(DataTable((6-k), Globaldt))
Check_TypedData(DataTable((6-k), Globaldt))
End If
Type_Key(Operation)
Else
Exit Function
End If
End Function
'****************** Arithemetic Functions*******************
Public Function Arithemetic (Operator)
Select Case Operator
Case "Add"
Numbers=3
Operation="\+"
Case "Multiply"
Numbers=3
Operation="\*"
Case "Subtract"
Numbers=2
Operation="\-"
Case "Divide"
Numbers=2
Operation="\/"
End Select
For k=1 to Numbers
Call Perform_Operation (k, Numbers, Operation)
Next
If Environment.Value("Incorrect_Input")= 0 Then
Ans=Window("Calculator").WinEdit("Input_Output Box").GetROProperty("text")
Ans=Round (Ans,2)
DataTable (Operator, Globaldt)=Ans
Window("Calculator").WinButton("Clear").Click
Else
Window("Calculator").WinButton("Clear").Click
Exit Function
End If
End Function
'************* Start Calculator ***************
Public Function Open_Calculator()
SystemUtil.Run "C:\WINDOWS\system32\calc.exe"
End Function
'******************** Load Data ********************************
Public Function Load_Data()
DataTable.Import("D:\Ranger Automation\Learn QTP\Calculator_Exc\Data File\" & Environment.Value("Load_Data") & ".xls")
End Function
'************ Check Input Rows *****************************
Public Function Check_Input (Start_Row, End_Row)
If (Start_Row > End_Row) Then
Msgbox ("The data entered is invalid. End Row can not be less than the Start Row")
Window("Calculator").Close
ExitTest
End If
End Function
'*************Call Arithemetic Function **************
Public Function Call_Arithemetic (Set_Row)
DataTable.SetCurrentRow(Set_Row)
Arithemetic ("Add")
Arithemetic ("Multiply")
Arithemetic ("Subtract")
Arithemetic ("Divide")
Validate_Data(Set_Row)
End Function
''********** Getting the number split into digits***************
Public Function Get_Digits (Num)
Length_Num=Len(Num)
Do Until Length_Num=0
Digit=Left (Num, 1)
Type_Key(Digit)
Num=Right(Num,(Length_Num-1))
Length_Num=Length_Num-1
Loop
End Function
'*************Typing the keys in the calculator*****************
Public Function Type_Key(input)
If input="." Then
Window("Calculator").WinButton("Decimal").Click
Else
Window("Calculator").WinButton("text:="&input).Click
End If
End Function
'***************Save and Close Calculator ********************
Public Function SaveClose(File_Name)
sPath="D:\Ranger Automation\Learn QTP\Calculator_Exc\Results\" & File_Name & ".xls"
DataTable.Export (sPath)
Window("Calculator").Close
Dialog("Windows Task Manager").Close
End Function
'************* Add Status Column *************
Public Function Add_Parameter
DataTable.GetSheet(1).AddParameter "Status", ""
DataTable.GetSheet(1).AddParameter "Description", ""
DataTable.DeleteSheet(2)
DataTable.AddSheet("Task_Manager")
DataTable.GetSheet(2).AddParameter "Percentage", ""
DataTable.GetSheet(2).AddParameter "Memory_Usage", ""
DataTable.GetSheet(2).AddParameter "Peak_Memory_Usage", ""
SystemUtil.Run "taskmgr.exe"
Selection = Dialog("Windows Task Manager").WinTab("text:=Tab", "regexpwndclass:=SysTabControl32").GetROProperty("selection")
If Selection <> "Processes" Then
Dialog("Windows Task Manager").WinTab("text:=Tab", "regexpwndclass:=SysTabControl32").Select "Processes"
End If
End Function
'*************** Validate the data *******************
Public Function Validate_Data(Set_Row)
If Environment.value("Incorrect_Input") = 0 Then
Set Excel= CreateObject("Excel.Application")
sPath = "D:\Ranger Automation\Learn QTP\Calculator_Exc\Data File\" & Environment.Value ("Expected_Results") &".xls"
Set Book=Excel.Workbooks.Open(sPath)
Excel.Visible = True
Set Sheet= Book.Worksheets("Global")
Flag = 0
For Col = 4 to 7
If Flag = 0 Then
Actual = DataTable(Col, Globaldt)
Actual = Round (Actual, 2)
Expected = Sheet.Rows(Set_Row+1).Columns(Col)
If Actual = Expected Then
DataTable("Status", Globaldt) = "Pass"
Else
DataTable("Status", Globaldt) = "Fail"
Flag =1
Reporter.ReportEvent micFail, "Data Incorrect", "Data in Row " & Set_Row& " Column "& Col & " is Incorrect"
DataTable("Description", Globaldt) = "Data in Col "& Col & " is Incorrect. The expected value is " & Expected
End If
ElseIf Flag = 1 Then
Exit For
End If
Next
Book.Close
Else
Exit Function
End If
End Function
'*********************** Task Manager ****************************
Public Function Task_Manager()
DataTable.GetSheet(2).SetCurrentRow(Environment.Value("SetRow"))
mem =Dialog("Windows Task Manager").WinlistView("Image Name").GetSubItem("calc.exe", "Mem Usage")
peak = Dialog("Windows Task Manager").WinlistView("Image Name").GetSubItem("calc.exe", "Peak Mem Usage")
DataTable("Percentage", "Task_Manager")= Environment.Value("Percentage")
DataTable("Memory_Usage", "Task_Manager")=mem
DataTable("Peak_Memory_Usage", "Task_Manager") = peak
Environment.Value("Percentage") = Environment.Value("Percentage") + 25
Environment.Value("SetRow") = Environment.Value("SetRow") + 1
End Function
Main
Open_Calculator
Check_Launch
Load_Data
Check_RowCount
Add_Parameter
For Set_Row= 1 to 10
If Set_Row = 1or Set_Row = 7 or Set_Row = 14 or Set_Row = 20 or Set_Row = 25 Then
Task_Manager()
End If
Environment.Value("Incorrect_Input")=0
Call_Arithemetic (Set_Row)
Next
File_Name=InputBox("Enter the file name f or the Results file")
SaveClose(File_Name)
Functions
********* Application Launch Checkpoint ***********************
Public Function Check_Launch()
Wait 2
If Window("Calculator").Exist Then
Reporter.ReportEvent micPass, "Application Launch", "The application has launched successfully"
Else
Reporter.ReportEvent micFail, "Application Launch", "The application has failed to launch"
End If
End Function
'******** Check Row Count ****************************
Public Function Check_RowCount()
RowCount = DataTable.GetRowCount
If RowCount=25 Then
Reporter.ReportEvent micPass, "RowCount", "There are 25 rows of data"
Else
Reporter.ReportEvent micFail, "RowCount", "Incorrect Row Count. It should be 25 instead of "&RowCount
End If
End Function
'******* Check the typed data *************
Public Function Check_TypedData(Num)
Text= Window("Calculator").WinEdit("Input_Output Box").GetROProperty("text")
Text=clng (Text)
Text=RTrim(Text)
Text=LTrim(Text)
If Text = Num Then
Reporter.ReportEvent micPass, "TypedText", "The typed data is the same as in the input file"
Else
Reporter.ReportEvent micFail, "TypedText", "The typed data does not match the data in the input file"
Environment.Value ("Incorrect_Input") = 1
DataTable("Status", Globaldt)= "Fail"
DataTable("Description", Globaldt) = "Entered number " & Num & " and Calculator output " & Text & " do not match"
End If
End Function
'*********************** Check the Output Data *****************
Public Function Perform_Operation (k, Numbers, Operation)
If Environment.Value ("Incorrect_Input") = 0 Then
If Numbers=3 Then
Get_Digits(DataTable(k,Globaldt))
Check_TypedData (DataTable(k,Globaldt))
Else
Get_Digits(DataTable((6-k), Globaldt))
Check_TypedData(DataTable((6-k), Globaldt))
End If
Type_Key(Operation)
Else
Exit Function
End If
End Function
'****************** Arithemetic Functions*******************
Public Function Arithemetic (Operator)
Select Case Operator
Case "Add"
Numbers=3
Operation="\+"
Case "Multiply"
Numbers=3
Operation="\*"
Case "Subtract"
Numbers=2
Operation="\-"
Case "Divide"
Numbers=2
Operation="\/"
End Select
For k=1 to Numbers
Call Perform_Operation (k, Numbers, Operation)
Next
If Environment.Value("Incorrect_Input")= 0 Then
Ans=Window("Calculator").WinEdit("Input_Output Box").GetROProperty("text")
Ans=Round (Ans,2)
DataTable (Operator, Globaldt)=Ans
Window("Calculator").WinButton("Clear").Click
Else
Window("Calculator").WinButton("Clear").Click
Exit Function
End If
End Function
'************* Start Calculator ***************
Public Function Open_Calculator()
SystemUtil.Run "C:\WINDOWS\system32\calc.exe"
End Function
'******************** Load Data ********************************
Public Function Load_Data()
DataTable.Import("D:\Ranger Automation\Learn QTP\Calculator_Exc\Data File\" & Environment.Value("Load_Data") & ".xls")
End Function
'************ Check Input Rows *****************************
Public Function Check_Input (Start_Row, End_Row)
If (Start_Row > End_Row) Then
Msgbox ("The data entered is invalid. End Row can not be less than the Start Row")
Window("Calculator").Close
ExitTest
End If
End Function
'*************Call Arithemetic Function **************
Public Function Call_Arithemetic (Set_Row)
DataTable.SetCurrentRow(Set_Row)
Arithemetic ("Add")
Arithemetic ("Multiply")
Arithemetic ("Subtract")
Arithemetic ("Divide")
Validate_Data(Set_Row)
End Function
''********** Getting the number split into digits***************
Public Function Get_Digits (Num)
Length_Num=Len(Num)
Do Until Length_Num=0
Digit=Left (Num, 1)
Type_Key(Digit)
Num=Right(Num,(Length_Num-1))
Length_Num=Length_Num-1
Loop
End Function
'*************Typing the keys in the calculator*****************
Public Function Type_Key(input)
If input="." Then
Window("Calculator").WinButton("Decimal").Click
Else
Window("Calculator").WinButton("text:="&input).Click
End If
End Function
'***************Save and Close Calculator ********************
Public Function SaveClose(File_Name)
sPath="D:\Ranger Automation\Learn QTP\Calculator_Exc\Results\" & File_Name & ".xls"
DataTable.Export (sPath)
Window("Calculator").Close
Dialog("Windows Task Manager").Close
End Function
'************* Add Status Column *************
Public Function Add_Parameter
DataTable.GetSheet(1).AddParameter "Status", ""
DataTable.GetSheet(1).AddParameter "Description", ""
DataTable.DeleteSheet(2)
DataTable.AddSheet("Task_Manager")
DataTable.GetSheet(2).AddParameter "Percentage", ""
DataTable.GetSheet(2).AddParameter "Memory_Usage", ""
DataTable.GetSheet(2).AddParameter "Peak_Memory_Usage", ""
SystemUtil.Run "taskmgr.exe"
Selection = Dialog("Windows Task Manager").WinTab("text:=Tab", "regexpwndclass:=SysTabControl32").GetROProperty("selection")
If Selection <> "Processes" Then
Dialog("Windows Task Manager").WinTab("text:=Tab", "regexpwndclass:=SysTabControl32").Select "Processes"
End If
End Function
'*************** Validate the data *******************
Public Function Validate_Data(Set_Row)
If Environment.value("Incorrect_Input") = 0 Then
Set Excel= CreateObject("Excel.Application")
sPath = "D:\Ranger Automation\Learn QTP\Calculator_Exc\Data File\" & Environment.Value ("Expected_Results") &".xls"
Set Book=Excel.Workbooks.Open(sPath)
Excel.Visible = True
Set Sheet= Book.Worksheets("Global")
Flag = 0
For Col = 4 to 7
If Flag = 0 Then
Actual = DataTable(Col, Globaldt)
Actual = Round (Actual, 2)
Expected = Sheet.Rows(Set_Row+1).Columns(Col)
If Actual = Expected Then
DataTable("Status", Globaldt) = "Pass"
Else
DataTable("Status", Globaldt) = "Fail"
Flag =1
Reporter.ReportEvent micFail, "Data Incorrect", "Data in Row " & Set_Row& " Column "& Col & " is Incorrect"
DataTable("Description", Globaldt) = "Data in Col "& Col & " is Incorrect. The expected value is " & Expected
End If
ElseIf Flag = 1 Then
Exit For
End If
Next
Book.Close
Else
Exit Function
End If
End Function
'*********************** Task Manager ****************************
Public Function Task_Manager()
DataTable.GetSheet(2).SetCurrentRow(Environment.Value("SetRow"))
mem =Dialog("Windows Task Manager").WinlistView("Image Name").GetSubItem("calc.exe", "Mem Usage")
peak = Dialog("Windows Task Manager").WinlistView("Image Name").GetSubItem("calc.exe", "Peak Mem Usage")
DataTable("Percentage", "Task_Manager")= Environment.Value("Percentage")
DataTable("Memory_Usage", "Task_Manager")=mem
DataTable("Peak_Memory_Usage", "Task_Manager") = peak
Environment.Value("Percentage") = Environment.Value("Percentage") + 25
Environment.Value("SetRow") = Environment.Value("SetRow") + 1
End Function
Thursday, July 29, 2010
Sentence to Words
This is how you can convert a sentence to word. This is helpful when u get the object property as a string and then need to separate it into words for further processing. This is also very helpful in the Data Driven framework, where the criterion for running the tst suites may be provided in strings.
Str = Window(" ").Object(" ").GetVisibleText
Var = Split(Str, "delimiter") ' The delimiter can be a space or comma or $ symbol etc
Len_Array = UBound (Var)
For i = 0 To Len_Array
Str_1 = Var(i)
Msgbox Str_1
Next
Str = Window(" ").Object(" ").GetVisibleText
Var = Split(Str, "delimiter") ' The delimiter can be a space or comma or $ symbol etc
Len_Array = UBound (Var)
For i = 0 To Len_Array
Str_1 = Var(i)
Msgbox Str_1
Next
Task Manager
This is the sample code for getting the memory usage and peak memory usage for an application using QTP and writing it out in the DataTable. Here we are using the calc.exe application. This method can be used to get the data from any WinList View object.
SystemUtil.Run "taskmgr.exe"
Selection = Dialog("Windows Task Manager").WinTab("text:=Tab", "regexpwndclass:=SysTabControl32").GetROProperty("selection")
If Selection <> "Processes" Then
Dialog("Windows Task Manager").WinTab("text:=Tab1", "regexpwndclass:=SysTabControl32").Select "Processes"
End If
mem =Dialog("Windows Task Manager").WinlistView("Image Name").GetSubItem("calc.exe", "Mem Usage")
peak = Dialog("Windows Task Manager").WinlistView("Image Name").GetSubItem("calc.exe", "Peak Mem Usage")
DataTable("Percentage", "Task_Manager")= Environment.Value("Percentage")
DataTable("Memory_Usage", "Task_Manager")=mem
DataTable("Peak_Memory_Usage", "Task_Manager") = peak
SystemUtil.Run "taskmgr.exe"
Selection = Dialog("Windows Task Manager").WinTab("text:=Tab", "regexpwndclass:=SysTabControl32").GetROProperty("selection")
If Selection <> "Processes" Then
Dialog("Windows Task Manager").WinTab("text:=Tab1", "regexpwndclass:=SysTabControl32").Select "Processes"
End If
mem =Dialog("Windows Task Manager").WinlistView("Image Name").GetSubItem("calc.exe", "Mem Usage")
peak = Dialog("Windows Task Manager").WinlistView("Image Name").GetSubItem("calc.exe", "Peak Mem Usage")
DataTable("Percentage", "Task_Manager")= Environment.Value("Percentage")
DataTable("Memory_Usage", "Task_Manager")=mem
DataTable("Peak_Memory_Usage", "Task_Manager") = peak
Subscribe to:
Posts (Atom)