Sunday, March 17, 2013

How to compare two images using QTP

We know by using Bitmap checkpoint, we can compare two images.

But is there a other way we can compare?

Yes, we can use "IsEqualBin" method from Mercury.FileCompare

sImgPath1="C:\Users\user\Downloads\SAI 01461_exposure.JPG"
'sImgPath2="C:\Users\user\Downloads\SAI 01462_exposure.JPG"
sImgPath2="C:\Users\user\Downloads\SAI 0175_exposure.JPG"
Set obj=createobject("Mercury.FileCompare")
retVal=obj.IsEqualBin(sImgPath1,sImgPath2,1,1)
print retVal
Set obj=nothing

The retVal=1 if both the images are same
else retVal=0

Monday, March 4, 2013

How to add an image at the end of the Word document

Here i divided the task into 2 steps.
1. Capture the desktop image/application.
2. Insert the captured image at the end of the word document.

sImageFilePath="D:\TempImage.png"
sWordFilePath="D:\Programming Samples\QTP\SampWord.docx"

CapturePrintScreen sImageFilePath
AddImageToWord sWordFilePath,sImageFilePath

Sub CapturePrintScreen(sFilePath)
   Desktop.CaptureBitmap sFilePath,true
End Sub

Sub AddImageToWord(sWrdFilePath,sImgFilePath)
   Const END_OF_STORY = 6
    Const MOVE_SELECTION = 0
   Set oWord=createobject("Word.Application")
    oWord.Visible=true

    set oDoc=oWord.Documents.Open(sWrdFilePath)

    Set oSelection=oWord.Selection
    oSelection.EndKey END_OF_STORY,MOVE_SELECTION

    oSelection.InlineShapes.AddPicture(sImgFilePath)

    oDoc.Save

    oWord.Application.Quit
   
    Set oWord=nothing
End Sub

Thursday, February 7, 2013

QTP unables to identify pop up window


There are couple of scenarios where we perform some operations in a application, where a pop up window will appear like:
1. When you delete a user/emp, it will display a pop up saying "Do you want to Delete the user?"
2. You choose some pop up menu option, then a pop up window may be displayed with the selected items functionality.

For sometimes, even though you have the correct recorded script, it may throw you an error saying the object does not exist.

Ex: B("XYZ").Dialog("Delete User").WinButton("Ok").click    may throw error saying "Object not visible".

How to overcome this error?

Cause: The "visible" property of the Parent object may not enabled.

Solution: Goto Tools -> Object Identification -> Choose Environment type -> Choose the object class(in our case Browser is the parent to the Dialog box) -> Click on Add/Remove property -> select "visible" property.
After visibility property is configured, now re-record the steps.

Now QTP should be able to identify the pop up window.

Tuesday, February 5, 2013

How to get QTP Results in a HTML file

Once we ran our Regression suite, it is handy if the results are displayed in HTML File, it is easy for us to understand at the same time also easy for the management(Lead/Manager/Customer) to look at it.

They will not show any interest if you zip your QTP Result folders and send it to them.

And for many reasons it is handy if the results are displayed in HTML File, right? How can we get the results in HTML File.

But how can we view results in HTML File?

By changing one registry setting, we have get QTP results in a HTML File.

Open windows registry by entering regedit and clicking enter in Windows run.

HKLM\Software\MercuryInteractive\QuickTestProfessional\Logger\Media\Log

Double click on "Active"

Change the value from 0 to 1.

Restart QTP.

Now run your QTP Test and see results in the QTP Test folder, where you see a "Log" folder.

In this folder you will see a file called LogFile.html which is the HTML Report.

Friday, February 1, 2013

How to check the website you are testing is up and running

We can check the website up and running by just pinging the website.

You can do that in couple of ways.

Here is the simplest way to  ping a website.

Appraoch1:

strWebSiteName="www.yahoo.com"
strQuery = "SELECT * FROM Win32_PingStatus WHERE Address = '" & strWebSiteName & "'"
bFlag = False

Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
Set objItems = objWMIService.ExecQuery( strQuery )

For Each objItem In objItems
       If objItem.StatusCode = 0 Then
            bFlag = True
            Exit For
        Else
            bFlag = False
        End If
Next

If bFlag = true Then
    print "Website is avilable"
else
    print "Website not avilable"
End If

Set objItems = Nothing
Set objWMIService = Nothing

Appraoch2:
Set oNetwork = DotNetFactory( "Microsoft.VisualBasic.Devices.Network" ,"Microsoft.VisualBasic")
bFlag=oNetwork.ping(strWebSiteName)
If bFlag Then
  print  "Website is avilable"
Else
   print  "Website not avilable"
End If
Set oNetwork=nothing

Saturday, January 19, 2013

How to check an Excel file is already open

There are no direct methods using Exel/Workbook object to find the functionality.

Work around is, we need to find out all open tasks, and from that we will see whether any task with name "Microsoft Excel"

Here in the below code, i have a sample Excel file with name "SampleXL".

Set Word = CreateObject("Word.Application")
Set Tasks = Word.Tasks
i=0
For Each Task in Tasks
    If instr(Task.Name,"Microsoft Excel - SampleXL")>0  Then
            i=1
    end if
Next
If i=1 Then
    print "Excel file is opened"
else
    print "No excel file opened with the name specified"
End If

Word.Quit

How to retrieve data from Excel file using ADODB

The below code retrieves data from Sheet1 from an Excel file using ADODB.

Both the connection strings specified here works.

Set oCmd=createobject("ADODB.Command")
Set oRS=createobject("ADODB.RecordSet")

sCon="Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=D:\Programming Samples\QTP\SampleXL.xls;"
'sCon="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Programming Samples\QTP\SampleXL.xls;Extended Properties=""Excel 8.0;"""
sQry="select * from [Sheet1$]"

oCmd.ActiveConnection = sCon
oCmd.CommandText=sQry
Set oRS=oCmd.Execute
While not oRS.EOF
    print oRS.Fields(1).Value
    oRS.MoveNext
Wend

oRS.Close

Set oCmd=nothing
Set oRS=nothing

How to verify the existance of an environmental variable

The below code illustrate the existence of an environmental variables:

function checkEnvironmentalVariableExists(sEnvVarName)
    Err.clear
    On error resume next
    envValue=Environment.Value(sEnvVarName) 'Env exist
    If Err.number<>0 Then
        checkEnvironmentalVariableExists=False
    else
        checkEnvironmentalVariableExists=true
    End If
    On error goto 0
end function

Environment.Value("name")="Uday"
retVal=checkEnvironmentalVariableExists("name123")
If retVal=true Then
    print "Environmental Variable exists"
else
    print "Environmenta Variable does not exist"
End If

Tuesday, January 1, 2013

How to check a browser window is minimized

Extern.Declare micLong, "GetMainWindow", "user32" ,"GetAncestor",micLong, micLong 'This is the declaration for the referencing "GetMainWindow" with the GetAncestor method in user32.dll.
GA_ROOT=2

Just opened Gmail and checked whether the browser is minimized or maximized.

We cannot directly use Browser().GetROProperty("minimized") here.


Set oBrowser=description.Create
oBrowser("micclass").value="Browser"
oBrowser("name").value="Gmail.*"

hwnd=Browser(oBrowser).GetROProperty("hwnd")

hwnd = Extern.GetMainWindow(hwnd , GA_ROOT)
msgbox Window("hwnd:=" & hwnd ).GetROProperty("minimized")

The above code returns False if the Tab/browser is maximized else
returns True if the Tab/browser is minimized

The above code worked well with QTP and IE 7.

How to display occurances of a string in a Excel file

Following code helps find the occurrences of a string in a Excel file.

It will return the count as 0, if the string is not found
else returns the number of occurrences of the string

Dim oXLObj,oXLWBObj,olXLWSObj

Function FindStringOccuranceCount(sFileName,iSheetId,sSearchString)
    iCount=0
    set oXLObj=createobject("Excel.Application")
    Set oXLWBObj=oXLObj.workbooks.open(sFileName)
    Set olXLWSObj=oXLWBObj.worksheets(1)

    set cell=olXLWSObj.Range("A:Z").find(sSearchString)
   

    If cell is nothing Then
        CloseExcel()
        FindStringOccuranceCount=iCount
        Exit Function
    End If

    sFirstAddress=cell.address

    Do
        set cell=olXLWSObj.Range("A:Z").FindNext(cell)
        'set CurCell=olXLWSObj.UsedRange.FindNext(sSearchString)
        sCurrentAddress=cell.address
        'sCurrentAddress
        iCount=iCount+1
    loop while not cell is nothing and sCurrentAddress<>sFirstAddress

    CloseExcel()
    FindStringOccuranceCount=iCount

End Function

Function CloseExcel()
    oXLWBObj.close
    oXLObj.application.quit
    Set oXLWBObj=nothing
    Set oXLObj=nothing
End Function

x=FindStringOccuranceCount("C:\Test1.xls",1,"Uday")
msgbox x

Sample Excel file is here:

Wednesday, December 19, 2012

QTP built-in environmental variables

I found people forget the all the built-in environmental variables, so thought of putting all built-in variables here in this post.

ActionIteration - Indicates which action iteration is currently running.
ActionName - Indicates which action is currently running
ControllerHostName - the name of the computer which serves as a controller
GroupName - The scenario identification number
LocalHostName - Local Host Name
OS - Operation System
OSVersion - Operating system version
ProductDir - folder path where the product is installed
ProductName - Product Name
ProductVer - Product Version
ResultDir - Folder path where the results are saved
Scenarioid - The scenario identification number
SystemTempDir - System Temporary Directory
TestDir - Path of the Test
TestIteration - Indicates which test iteration is currently running
TestName - The name of the test
UpdatingActiveScreen -
UpdatingCheckpoints -
UpdatingTODescriptions -
UserName - Windows Login User Name
VUserId -

Friday, November 9, 2012

How to find CPU and Memory Usage using QTP

How to find out CPU utilization and Memory usage as displayed in the Windows Task Manager.

We can get these values using WMI service.


Below is the code:
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

'Get the CPU utilization %
myQuery = "SELECT * FROM Win32_PerfFormattedData_PerfOS_Processor WHERE Name = '_Total'"
For Each objItem in objWMIService.ExecQuery(myQuery)
   print "Processor time " & objItem.PercentProcessorTime & "  %"
next

'Get the total Physical Memory
myQuery="Select * from Win32_ComputerSystem"
Set colItems = objWMIService.ExecQuery(myQuery)
For each objitem in colItems
    print "Total Physical Memory "&objitem.TotalPhysicalMemory/1024
Next

'Get the total available physical memory
myQuery="Select * from Win32_PerfFormattedData_PerfOS_Memory"
Set colItems = objWMIService.ExecQuery(myQuery)
For Each objItem in colItems
    print "Available GB: " & objItem.AvailableKBytes
Next

Wednesday, November 7, 2012

How to execute QTP scripts in a remote machine when the window is minimized?

QTP Version : 11 or later
RDP Version : 6 or later

If you want to run QTP scripts run on a remote machine and if that Remote machine/Window is minimized, then the scripts will fail.

In order to overcome the issue, you need to add a registry key in Windows registry on your client machine/from the machine where you initiating the remote desktop.
1. Close all your remote desktops.
2. Create a registry "RemoteDesktop_SuppressWhenMinimized" if does not exist in the below path:
   HKEY_CURRENT_USER\Software\Microsoft\Terminal ServerClient\RemoteDesktop_SuppressWhenMinimized
   or
   HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Terminal Server Client\RemoteDesktop_SuppressWhenMinimized
3. Set the value for this data to 2.

If you would like to add the registry key by just running a .reg file follow below steps:
1. Open Notepad.
2. Cope the below content:
 Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\Microsoft\Terminal ServerClient\RemoteDesktop_SuppressWhenMinimized]
"RemoteDesktop_SuppressWhenMinimized"=dword:00000002

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Terminal Server Client\RemoteDesktop_SuppressWhenMinimized]
"RemoteDesktop_SuppressWhenMinimized"=dword:00000002
3. Save the file as "FileName.reg" format
4. Now, double click on this reg file, so that registry keys will be added.

Saturday, July 28, 2012

How to activate, minimize, maximize a browser using QTP

You can use below code to active, minimize, maximize a browser. I put all these three methods in a single function, but you need to tweek this code as per your needs.

Function WinActivate(Object)
   Dim hWnd
    hWnd = Object.GetROProperty("hwnd") 'First get the window handle
    On Error Resume Next
    Window("hwnd:=" & hWnd).Activate 'Put fouse on the window
    If Err.Number <> 0 Then
            hWnd=Browser("hwnd:=" & hWnd).Object.hWnd 'now get the browser handle
            Window("hwnd:=" & hWnd).Activate 
            'Window("hwnd:=" & hWnd).minimize 'To minimize the browser
            'Window("hwnd:=" & hWnd).maximize
            Err.Clear
    End If
    On Error Goto 0
End Function

RegisterUserFunc "Browser","Activate","WinActivate"
RegisterUserFunc "Browser","Minimize","WinMinimize"
RegisterUserFunc "Browser","Maximize","WinMaximize"

Browser(objBrowser).Activate
Browser(objBrowser).Minimize
Browser(objBrowser).Maximize

Saturday, June 30, 2012

How to verify a Browser Window is minimized

The bad part is  QTP does not support retrieving RO Properties of a browser. If it has supported, then we would have use a method like Browser("Browser Name").GetROProperty("minimized")




















But we can use Extern to use some of the methods from Windows user32.dll
Following are the two ways to verify the window minimized.
Extern.Declare micHwnd, "FindWindow", "user32.dll","FindWindowA", micString,micString 'this method returns a handle
Extern.Declare micLong,"GetWindowMinimizeState", "user32.dll" ,"IsZoomed",micLong 'IsZoomed meaning IsMaximized
hwnd=extern.FindWindow(NULL,"Links - Windows Internet Explorer")
print Extern.GetWindowMinimizeState(hwnd) 'Similar way


Const GA_ROOT = 2
'Declare Function GetAncestor Lib "user32.dll" (ByVal hwnd As Long, ByVal gaFlags As Long) As Long Extern.Declare micLong, "GetMainWindow", "user32" ,"GetAncestor",micLong, micLong
hwnd = browser("name:=Links.*").GetROProperty("hwnd") 'this returns the handle of the Browser Tab hwnd = Extern.GetMainWindow(hwnd , GA_ROOT) 'This returns the handle of the browser(which means handle of the browser)
msgbox Window("hwnd:=" & hwnd ).GetROProperty("minimized")

How to find and fill a color in Excel Cell

Set xlObj=getobject("","Excel.Application")
Set xlWBObj=xlObj.workbooks.open("c:\delete.xls")
set xlWSObj=xlWBObj.worksheets(1)
xlWSObj.cells(1,1).Font.Color=vbRed  'This statement changes the color of the Text in the specified cell
xlWSObj.cells(2,1).Interior.ColorIndex=4 'This method changes the color of the background of the cell
print  xlWSObj.cells(1,1).Font.Color
print xlWSObj.cells(2,1).Interior.ColorIndex
xlWBObj.save
xlWBObj.close
xlObj.application.quit
Set xlObj=nothing

Monday, April 30, 2012

How to copy content to Clipboard

We can use clipboard using two ways.
One is using Mercury.Clipboard.
Second one is using DotNetFactory.


Using Mercury.Clipboard:
'Creates an instance of Mercury.Clipboard
set objCB=createobject("Mercury.Clipboard")
'Here i am clearing already existing content in clipboard
objCB.Clear()
'Copying some text into Clipboard
objCB.SetText("Hello Uday")
'Retrieving the content from Clipboard
print objCB.GetText

Using DotNetFactory:
'Creates an instance of DotNetFactory Computer Object
Set objDFComputer=DotNetFactory("Microsoft.VisualBasic.Devices.Computer","Microsoft.VisualBasic")
'Here i am clearing already existing content in clipboard
Set objCB=objDFComputer.ClipBoard
objCB.clear()
'Copying some text into Clipboard
objCB.SetText("Hello Uday")
'Retrieving the content from Clipboard
print objCB.GetText

Sunday, April 29, 2012

"Setting" utility object to access registry values

We can obtain and configure all the QTP configurable parameters(all parameters in MicTest) using "Setting" utility object. Ex: BrowserType, DefaultLoadTime etc...
For Ex: If you want to retrieve the default location of saving your tests, which exists in HKLM\Software\Mercury Interactive\QuickTest Professional\MicTest\TestsDirectory, you can use below line of code:
Setting
print Setting("TestsDirectory")

You can also use Setting.Item to retrieve the value of the parameter. For the above, you can also use like:
print Setting.Item("TestsDirectory")

If you want to access a parameter exists in folders, then you can use
Setting("")("Child1")("Child2)("PropertyName")

Here is the Ex. to access the Add-In Manager name for Visual Basic.
print Setting("AddIn Manager")("VisualBasic")("Name")


Thursday, March 15, 2012

Pure virtual function call


Suddenly QTP behaves very strangely. You cannot save any Tests etc etc... and it throws an error message saying R6025 - Pure Virtual Function call. You cannot do much after this error.
Reinstalling QTP also less useful.

Possible causes might be:
QTP configuration files might be corrupt.
Not properly handling pointers in QTP, meaning not properly releasing the objects like Excel, ObjectRepository objects etc...
QTP provides patch for this. Install the patch QTP_00604 or QTP_00626.

IE scripts are failing or Objects are not recognized in IE.

Scripts are failing when IE is upgraded.
User has scripts developed in IE 6 and they worked fine.
But user updated his IE to IE7, then the scripts which worked earlier are failing now in IE 7.

Reasons could be:
BHOManager add-in could be disabled in IE7.
This add-in is needed for QTP to interact with IE.
Enable this Add-in by:
Open IE -> Tools Menu -> Manage Add-ons -> Enable or Disable add-ons -> Select BHOManager Class
Check whether the add-on is enabled or not. It should be enabled.

Objects are properly recognized in IE 7, but not recognized in IE 8.
Reason could be: Protected mode in IE 8.
Check the above solution, then follow to disable the protected mode in IE.
Open IE -> Tools Menu -> Internet Options -> Security Tab -> Uncheck "Enable Protected Mode" check box.