Monday, December 19, 2011

Select custom button in SwfToolbar

/[TestComplete JScript]==============================
// Function:    SelectMainMenu
// Description: selects a menu item from Infragistic Main menu
// Parameters:
//  -pProcess  - process of the application
//  -oMenu     - main menu, object
//  -sMenuItem - menu item to select, string 
// Return: <none>
// NOTES: menu items should be splitted with "|" symbol, e.g. "File|Options", "Administration|Edit|Account Roles" 
function SelectMainMenu(pProcess, oMenu, sMenuItem)
{
  var aMenu = sMenuItem.split("|");
  var i, j; // counter
  var iX = 0, iY = 0; // coordinates for clicking
  var iCount; // menu items count for each toolbar/popup menu
  var obj; // temporary object for different menuitems
  var iLevels = aMenu.length-1;
  
  // * * * Selecting top level menu item...
  iCount = oMenu.ToolbarsManager.Toolbars.Item(0).Tools.Count; // number of menu items in main menu
  for(i = 0; i < iCount; i++)
  {
    obj = oMenu.ToolbarsManager.Toolbars.Item(0).Tools.Item(i);
    Log.Message("Checking menu '" + obj.CaptionResolved.OleValue + "'");
    if(obj.CaptionResolved.OleValue.match(aMenu[0]))
    {
      oMenu.Click(iX + obj.WidthResolved/2, iY + obj.Height/2);
      break;
    }
    else
    {
      iX += obj.WidthResolved*obj.VisibleResolved;
    }
  }
  
  // * * * After top level menu selected selecting other menus...
  //for(j = iLevels; j > 0; j--)
  for(j = 1; j <= iLevels; j++)
  {
  iX = 0; iY = 0;
  obj = pProcess.WinFormsObject("DropDownForm", "", 1).WinFormsObject("PopupMenuControlTrusted", "");
  iCount = obj.MenuAgent.MenuItems.Count;
  for(i = 0; i < iCount; i++)
  {
    Log.Message("Checking menu item '" + obj.MenuAgent.MenuItems.Item(i).Text.OleValue + "'");
    if(StrTran (obj.MenuAgent.MenuItems.Item(i).Text.OleValue, "&", "").match(aMenu[j]))
    {
      obj.Click(iX + 10, iY + 10);
      break;
    }
    else
    {
      iY += 25;
    }
  }
  } // j= iLevels...
}

Sunday, December 18, 2011

Select all rows in Infragistics.Win.UltraWinGrid.UltraGrid

I have found the way to select all rows in table and check whether all that rows is selected or not.


Public Function Swf_SelectAllItems(ByRef objSwfTable)
Dim strStep: strStep= "Swf_SelectAllItems()"
Dim numRows,i
If objSwfTable.GetROProperty("enabled") Then
numRows = objSwfTable.RowCount

objSwfTable.Type micLCtrlDwn

For i = 0 to numRows-1
objSwfTable.SelectRow i
objSwfTable.Type micDwn
Next
objSwfTable.Type micLCtrlUp
Dim iSelectedRows: iSelectedRows = objSwfTable.Object.Selected.Rows.Count
If  numRows = iSelectedRows Then
            reporter.ReportEvent micDone,strStep,"Success: Successfully Select All Items"
Swf_SelectAllItems=True
        Else
            reporter.ReportEvent micWarning,strStep, "Fail: Does NOT select All Items"
Swf_SelectAllItems=False
End If
Else
reporter.ReportEvent micWarning,strStep, "The : table is NOT ENABLE."
End If

End Function

Wednesday, December 7, 2011

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



Source: http://qtp-learnings.blogspot.com/2010/08/sending-mails-using-outlook-and-smtp.html

How to send email with attachment from outlook using qtp


 Code:
Text1 ="The information contained in this message " _
    & "constitutes privileged and confidential information " _
    & "and is intended only for the use of and review by " _
    & "the recipient designated above."
 
Text2= "The information contained in this message " _
    & "constitutes privileged and confidential information " _
    & "and is intended only for the use of and review by " _
    & "the recipient designated above."
 
'Multiline body
Body= Text1 & vbCrLf & Text2
 
'path of the file sample.txt  to be attached
path="D:\sample.txt"
 
'Usage of Function  "Send_Testresults"
'Multiple email Id can be used  with  semicolon as Seperator
Send_Testresults"xx@mail.com;yy@abc.com","zz@xyz.com",,"Mail from QTPWorld.com",Body,path
 
'Function  to send email
Function  Send_Testresults(sTo,sCC,sBCC,sSubject,sBody,sAttachment)
 
'Open outlook if Outlook is not open
   systemUtil.Run "OUTLOOK.EXE"
   wait (10)
 'Create Outlook Object
Set oMail = CreateObject("Outlook.Application")
 
set  Sendmail=oMail.CreateItem(0)
      Sendmail.To=sTo
      Sendmail.CC=sCC
      Sendmail.BCC=sBCC
      Sendmail.Subject=sSubject
      Sendmail.Body=sBody
          If (sAttachment <> "") Then
         Sendmail.Attachments.Add(sAttachment)
         End If 
 
       Sendmail.Send
 
oMail.quit
 
set  Sendmail=Nothing
set oMail=Nothing
 
End Function









Source: http://qtpworld.com/index.php?cid=89

Tuesday, October 4, 2011

Generate Logfile in HTML


There are a lot of different solutions for improved reporting in QTP (for example, our very own ReporterManager). However, sometimes, you simple wish to export the entire report into a single HTML file, in order to copy / mail / archive it. Here’s a neat trick that will help you do that:
Open the registry editor, and go to
HKLM->SOFTWARE->Mercury Interactive->QuickTest Professional->Logger->Media->Log
There’s an item named “Active” under that key. Change it to 1 (it should be 0)
Now when you run a test (you need to restart QTP after the change), the results folder will include a LOG folder, with the entire log as a single HTML file. It’s a concise report, but it’s quite enough for most user.
Source:  http://www.advancedqtp.com/2008/08/save-qtp-report-as-a-single-html-file/

Saturday, September 17, 2011

4 ways to get & count objects in QTP


4 ways to get & count objects in QTP

Imagine simple and practical QTP tasks:
  • How to count all links on Web page?
  • How to get them and click each link?
  • How to get all WebEdits and check their values?

I'm going to show 4 approaches how to get lists of UI controls and process them (for example get their count).
As an example, I will work with links on Google Labs page. My goal is to get the list of links and count them.

I've added Google Labs page to my Object Repository and now it looks like:
I use Object Repository (OR) to simplify my demo-scripts.
Since the browser & the page were added to OR, we can use them later like:
Browser("Google Labs").Page("Google Labs").

Now we are ready to start!

  1. QTP Descriptive Programming (QTP DP) and ChildObjects QTP function
    The approach uses Description object, which contains a 'mask'
     for objects we would like to get.
    QTP script is:
    Set oDesc = Description.Create()
    oDesc("micclass").Value = "Link"
    Set 
    Links = Browser("Google Labs").Page("Google Labs").ChildObjects(oDesc)
    Msgbox "Total links: " & Links.Count
    The result of this QTP script is:
    ChildObjects returns the collection of child objects matched the description ("micclass" is "Link") and contained within the object (Page("Google Labs")).

  2. Object QTP property and objects collections
    QTP can work with DOM:
    Set Links = Browser("Google Labs").Page("Google Labs").Object.Links
    Msgbox "Total links: " & Links.Length
    I use Object property of Page object. It represents the HTML document in a given browser window.
    This document contains different collections - formsframesimageslinks, etc.
    And we use Length property to get the number of items in a collection.

    The result is the same as for the previous QTP script:

  3. Object QTP property and GetElementsByTagName method
    Again, we can get access to 
    the HTML document and use its GetElementsByTagName method
    As the name says, 
    GetElementsByTagName method returns a collection of objects with the specified tag.
    Since we are going to get all link, we should use "a" tag.

    QTP script is:

    Set Links = Browser("Google Labs").Page("Google Labs").Object.GetElementsByTagName("a")
    Msgbox "Total links: " & Links.Length
    The result is the following:

    Note: There is another way how to select objects by tag name:
    Set Links = Browser("Google Labs").Page("Google Labs").Object.all.tags("a")
    Msgbox "Total links: " & Links.Length
    The result will be the same. 69 link will be found.

  4. XPath queries in QTP
    The idea of this approach is to use XPath queries on a source code of Web page.
    For example, "//a" XPath query returns all "a" nodes (= links) from XML file.

    There is one problem. Web page contains HTML code, which looks like XML code but actually it is not.
    For example:
    • HTML code can contain unclosed img or br tags, XML code cannot.
    • HTML code is a case-insensitive markup language, XML is a case-sensitive markup language, etc
      More details here.

    So, we have to convert HTML source code into XML. The converted code is named as XHTML.

    You can convert HTML documents into XHTML using an Open Source HTML Tidy utility.
    You can find more info about how to convert HTML code into XHTML code here.

    I will use the final QTP script from this page, a bit modified:

    ' to get an HTML source code of Web page
    HtmlCode = Browser("Google Labs").Page("Google Labs").Object.documentElement.outerHtml

    ' save HTML code to a local file
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set f = fso.CreateTextFile("C:\HtmlCode.html"True, -1)
    f.Write(HtmlCode)
    f.Close()

    ' run tidy.exe to convert HTML to XHTML 
    Set oShell = CreateObject("Wscript.shell")
    oShell.Run "C:\tidy.exe --doctype omit -asxhtml -m -n C:\HtmlCode.html", 1, True ' waits for tidy.exe to be finished

    ' create MSXML parser
    Set objXML = CreateObject("MSXML2.DOMDocument.3.0")
    objXML.Async = False 
    objXML.Load("C:\HtmlCode.html")

    XPath = "//a" ' XPath query means to find all links
    Set Links = objXML.SelectNodes(XPath)
    Msgbox "Total links: " & Links.Length
    Note: you can download tidy.exe here for above QTP script.

    This QTP script leads to the same results - 69 links found:
    (Click the image to enlarge it)

  5. Bonus approah 
    Why don't you count all Wen page objects manually? :) Open a source code of the page and start counting :)
    Just joking :)

Summary:
  • I shown 4 practical approaches how to count Web page links.Similarly you can process images, webedits, etc
  • Each approach gets a list of objects.
  • First approach (QTP DP + ChildObjects) is the most easy
  • Second & third approaches (Object + collectionsObject + GetElementsByTagName) will work on Internet Explorer, because they use DOM methods
  • Fours approach is biggest but it is more powerful. It allows to use complex XPath queries.

Source: http://motevich.blogspot.com/2008/11/4-ways-to-get-count-objects-in-qtp.html

How to execute a qtp script from command prompt?


It is very much possible to launch a QTP test from Command prompt and then run it. The script to open QTP and then load the test into QTP and run the test is given in the "Quick Test Automation reference" file which is given in the Documentation Folder.



The path to get the file and the code is "C:Program FilesMercury InteractiveQuickTest ProfessionalhelpAutomationObjectModel.chm"

I have taken this script from this file and changed the path of my test to be loaded and saved the file as a .vbs and executed it from the command prompt.

The script is given below for quick reference

Dim qtApp 'As QuickTest.Application ' Declare the Application object variable
Dim qtTest 'As QuickTest.Test ' Declare a Test object variable
Dim qtResultsOpt 'As QuickTest.RunResultsOptions ' Declare a Run Results Options object variable

Set qtApp = CreateObject("QuickTest.Application") ' Create the Application object 


qtApp.Launch ' Start QuickTest
qtApp.Visible = True ' Make the QuickTest application visible

' Set QuickTest run options 


qtApp.Options.Run.ImageCaptureForTestResults = "OnError"
qtApp.Options.Run.RunMode = "Fast" 

qtApp.Options.Run.ViewResults = False
qtApp.Open "E:\Test Scripts\actiTIME FunctionCalls Script", True ' Open the test in read-only mode 


' set run settings for the test 


Set qtTest = qtApp.Test

qtTest.Settings.Run.IterationMode = "rngIterations" ' Run only iterations 2 to 4
qtTest.Settings.Run.StartIteration = 2
qtTest.Settings.Run.EndIteration = 4
qtTest.Settings.Run.OnError = "NextStep" ' Instruct QuickTest to perform next step when error occurs

Set qtResultsOpt = CreateObject("QuickTest.RunResultsOptions") ' Create the Run Results Options object 


qtResultsOpt.ResultsLocation = "E:\Test Scripts\actiTIME FunctionCalls Script\Res1" ' Set the results location
qtTest.Run qtResultsOpt ' Run the test 

MsgBox qtTest.LastRunResults.Status ' Check the results of the test run 

qtTest.Close ' Close the test

Set qtResultsOpt = Nothing ' Release the Run Results Options object 

Set qtTest = Nothing ' Release the Test object
Set qtApp = Nothing ' Release the Application object 

For this you should have created a test with some actions in QTP and saved it then you need to specify the path of the test correctly at qtapp.Open

Save this file in a desired location with a .vbs extension.

Launch command prompt by going to run and type cmd and click enter.

The command prompt is visible. Since i store this .vbs file in E drive i have changed the directory in command prompt to E drive

C:\>E: and press enter

E:\> "This will be displayed" now enter the vbs file and click enter

E:\>testrun.vbs and clicked enter

Now the QTP will automatically launch load the specified test and runs it and gives you a message box prompt saying passed after the test is completed.


Read more: 
http://qtp4free.blogspot.com/2010/06/how-to-execute-qtp-script-from-command.html#ixzz1YDXbjYJe

5 THINGS TO TRY WHEN QTP DOES NOT RECOGNIZE AN OBJECT


by JOE COLANTONIO
What do you do when QuickTest Professional (QTP) doesn’t automatically recognize an object in your application? In my experience, these are the first five things to try/check:
1. Check the loaded add-ins:
It’s pretty basic, but be sure you have the correct add-ins selected. If QTP is only recognizing your objects as standard WinObject this may be a sign that you need to use an add-in. Sometimes QTP’s ‘Display Add-in’ Manager on start-up option, under Tools\Options\General may not be selected. This setting may cause you to start QTP on a machine and mistakenly assume that all of the correct add-ins have been chosen. Double-check by opening your script and selecting File\Settings under Properties ‘Associated add-ins:’ verifying that all the needed add-ins are listed. Also make sure QTP is started before the application under test. QTP will sometimes not recognize a web application if the browser was opened before QTP.
Add-Ins
Research the issue. If your add-ins are fine, the next step is to search the HP’s Knowledge base. Again, this may seem obvious, but a surprising number of people fail to do this. There’s nothing worse than spending hours on a script only to discover later that there is a patch (for example see patch that resolves some QTP 11 object issues) available or a posted solution that will solve the problem. I'm sometimes hailed as an automation genius by fixing something that an engineer may have been struggling with for days, based on information I found in the KB. Often, even after I tell the engineer how I solved the issue, they still don’t check the KB the next time they have a problem. Do me a favor -- don't be that guy (or gal)! Check the KB. (If nothing is found in the KB, another great resource to check is SQAForums.
3. Using .Object:
Look at all the available object’s operations (both the “identification properties” and “native properties” methods). You'll be surprised what you'll find lurking around in an object’s properties that may help to automate it. Using .Object try as many operations as possible--even ones that may not seem remotely relevant to the action you want to perform. For example: I was having a problem recognizing text on an application’s custom .NET grid. After spying on the object and trying several different methods that sounded promising, I ended up trying an odd one, called GetViewStyleInfo, and surprisingly it worked!


4. Try GetVisibleText:
Sometimes QTP does not recognize text in an object using the GetROProperty("text") method. As a last resort, try using the GetVisibleText, GetTextLocation and Type methods. These methods really helped me automate some old proprietary controls. Using a combination of QTP’s TYPE method and GetTextLocation, I created a very reliable rich edit box object function. For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
RichEditBoxICW "0","ENTER","=>","T","From date:" 
wait 1
RichEditBoxICW "0","ENTER","Through","T^20","Through date:" 
wait 1
RichEditBoxICW "0","ENTER","No=>","N","Do you want to queue this activity?" 
'***********************************
'* RICHEDITBOX
'**********************************
'************************
'* ICW
'* @Documentation  Used to perform valid actions on RichEdit objects.
'************************
Function RichEditBoxICW(index,action,lineText,valueToEnter,comment)
  
On Error Resume Next
  
'*****************************************
' SET OR PATH BASED ON ENV
'***************************************** 
set strICWPath = Browser("CF").Page("CF").Frame("WorkSpace").SwfObject("IEController")
 
strParse = strings("PARSE",valueToEnter,"LEFT","","") 'this would return False string does not contain ^
  
Select Case UCASE(action)
 Case "ENTER"
   intXY = getTextXY(lineText)
   arrXY = Split(intXY,"^")
   strICWPath.WinObject("regexpwndclass:=RichEdit20A").Click arrXY(0),arrXY(1)
     
     If strParse = "False"  Then
      Reporter.Filter = rfEnableAll
      strICWPath.WinObject("regexpwndclass:=RichEdit20A").Type micRight
      strICWPath.WinObject("regexpwndclass:=RichEdit20A").Type valueToEnter
      strICWPath.WinObject("regexpwndclass:=RichEdit20A").Type micReturn
      strReportMsg = "ENTERED ->" & valueToEnter
     ELSE
      strEnterValue = geString("PARSE",strValueToEnter,"LEFT","","")'Get Value to Enter
      strRightCount = geString("PARSE",strValueToEnter,"RIGHT","","")'Get # of right keys to press before entering text
      
     for nTabs = 1 to strRightCount
       strICWPath.WinObject("regexpwndclass:=RichEdit20A").Type micRight
     next
        
       strICWPath.WinObject("regexpwndclass:=RichEdit20A").Type strEnterValue
       strICWPath.WinObject("regexpwndclass:=RichEdit20A").Type micReturn 
                       
      strReportMsg = "ENTERED ->" & strEnterValue
   end select 
End Function
 
'---------------------------------------------------------
'@Function Name:   getTextXY
'@Documentation    Return X and Y coordinates of text
'@Parameters:        The text to find
'@Created By:        Joe Colantonio
'@Return Values:     X & Y coord separated by a ^
'@Example:            intXY = getTextXY(strLineText)
'-------------------------------------------------------------
Function getTextXY(strTextToFindXYFor)
  
set strICWPath = Browser("CF").Page("CF").Frame("WorkSpace").SwfObject("IEController")
  
  l = -1
  t = -1
  r = -1
  b = -1
 rc = strICWPath.WinObject("regexpwndclass:=RichEdit20A").GetTextLocation(strTextToFindXYFor, l, t, r, b)
  
 getTextXY = r & "^" & t
  
End function
5. Developers are your friend:
The application's developers can help you. Ask your developers to expose a method or add a property that will make automation easier. But before you ask -- make sure you've exhausted all the above suggestions. Developers can be a tough bunch, and you really don’t want to annoy them with things you could have resolved on your own. I work with some awesome programmers, and as long as I'm able to clearly explain to them what I need and why, they never hesitate to help.
These are my top 5 suggestions - what are yours?
Tip 5.1 - From Mike G Marshall "Another thing to check is “Record and Run” setting under Automation menu. If you try and identify an object in an application that doesn’t match the rules here, it will show as a standard Windows object."
Tip 5.2 - From Michael te Wierik - "I don’t know how many times I have slaved away to find a solution to an object identification issue, and then remembered to use “Low level recording” from the Automation menu when recording. Its a massive timesaver."
Sources: http://www.joecolantonio.com/2010/08/12/quicktest-object-recognition/