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

Showing posts with label QTP AOM. Show all posts
Showing posts with label QTP AOM. Show all posts

Properties for object identification in QTP

QTP learns the properties of test objects to uniquely identify the object at run time. There are predefined set of properties for object classes in each environment.


Object are classified as Object classes for each environment. For e.g. environment Standard Windows environment as shown below will have all the test object class defined and defined are the mandatory and assistive properties to identify the object. Also we can set smart identification On for the object and the default ordinal identifier.to identify the object. 


To have a look at Object Identification properties for an object, Navigate to Tools>Object Identifier.


Let us understand the object Identification Window:


1. Environment: Lists all the environment for which objects are defined.


2. Object Classes:
List all the controls available for the environment selected.


3. Mandatory Properties:
These are the properties QTP always learns for the test object class selected.


4. Assistive Properties: In case object is not uniquely identified using the mandatory properties, there are some assistive properties which are learned to uniquely identify the object.


5. Smart Identification
is false by default, but can be checked for identification.


6. Ordinal Identifer: In case object is not identified using the above properties , Ordinal identifier is used to identify the object

List of Regular Expression for UFT/QTP

Regular expression are used to match input text with the pattern provided by regular expression engine. A pattern consists of one or more character literals, operators, or constructs. Below table explains the different regular expression patterns to identify the input text matches the expected pattern


Regular expression are used to validate the input text provided with the expected pattern. e.g : validating date format is correct or telephone number  provided is in correct format.



Reg. Expression

Description

( .)

 A dot matches single character (.) eg test. will match dot followed by any single character.example: testa, test5 

 [ab]

Matches either of the character in the list. e.g 23[ab] will match both 23a or 23b but not 23r

[^ab]

Matches all the characters excluding the the character in the list. e.g 23[^ab] will not match both 23a or 23b but will match23r,235 or 23 followed by any character other

 \b

Matches a word at boundary. e.g test/b will match entest but not entester

 [x-y]

Matches a single character in the range. e.g 23[a-d] will match 23a,23b,23c,23d but not 23r

 [^x-y]

Matches a single character not in the range. e.g 23[^a-d] will not match 23a,23b,23c,23d but 23r

 \B

Matches a word not at boundary. e.g test/b will match entest but not entester

 \W

Matches any non-alphaNumeric character excluding underscore

 \w

Matches any alphaNumeric character including underscore

*

Wildcard character matching the multiple occurence of preceding character. e.g rat* will match ra, rat, rattt, ............i.e multiple occurence of preceeding character t in this example.

 .*

Wildcard character matching the multiple occurence of preceding character.Preceeding character is . in case, so ra.* will match any string starting with ra

+

Similar to * but atleast one occurence of the character should match.e.g : rat+ will match rat but not ra

 ?

 matches zero or one occurrences of the preceding character. For example: ra?t match rt or rat only

 |

Matches either of the character seperated by |.example nes(t|l)ey will match nestey or nesley.

 \d

Matches a digit character

\D

Matches a non- digit/numeric character

\

marks the next character as special character or a literal. e.g \n is for new line ; \\ for \ and \d for a digit character

^

matches the pattern at start of line. e.g: ^test will match testing, tester but not autotest.

 $

matches the pattern at end of line. e.g: test$ will match autotest but not tester.

 |

Matches either of the character seperated by |.example nes(t|l)ey will match nestey or nesley.

 {}

Matches the start and end of qualifier expression. e.g a{4,5} will match aaaa or aaaaa

Reference:  Regular Expression Language - Quick Reference

Types of Environment variables in QTP / UFT

Below are the types of environment variables in QTP


1) Built-in - Used to extract test specific and machine/OS information. E.g ActionName, LocalHostName and OS to name a few.


2) User-defined Internal - Defined for the test and available only to the test in which it is defined.


3) User-defined External - Can be used across tests and can be loaded from an external xml file dynamically at run time or at the test level.


More Details on this topic, click on Environment Variable Loading




UFT test information and failure reason from result.xml file

While running the UFT test in batch,we need to capture executed test information including testname, test execution status and reason for failure if any in the test execution. 
Below code in vbscript can be used to extract required information from results file (result.xml) in UFT and parsing the information in xml file using MSXML.DomDocument and Microsoft.XMLDOM


xmlFilePath = "c:\Results.xml"

Set xmlDoc = CreateObject("MSXML.DomDocument")
If xmlDoc.Load (xmlFilePath) Then
'Get the test name
 Set objNode = xmlDoc.GetElementsByTagName("DName")
 .TestName = objNode(0).Text
 Set objNode = xmlDoc.GetElementsByTagName("Summary")

 'Last Node with tagName "Summary" has details of Pass/Fail status
 Set Node = objNode(objNode.Length - 1)

 intStepsPassed = Node.getAttribute("passed")
 intStepsWarning = Node.getAttribute("warning")

 ''in case of failures get the testfailureReason
 If Cint(intStepsFailed) > 0 Then
  strFailureReason = getFailureReason(xmlFilePath)
 End if
 Set FSO = Nothing
 Set xmlDoc = Nothing
End If

Public function getFailureReason(strFileName)
 Set xmlDoc = CreateObject("Microsoft.XMLDOM")
 xmlDoc.async = False
 strErrorMsg = ""
 booleanxmlParse = xmlDoc.load(strFileName)
 if(booleanxmlParse) then
  xmlDoc.setProperty "SelectionLanguage", "XPath"
  set xmlDoc_node = xmlDoc.selectNodes("//Step//NodeArgs[@status='failed']")
  for each node in xmlDoc_node
   strNode = node.parentNode.getattribute("rID")
   set TCNode = xmlDoc.selectSingleNode("//Step[@rID='" + strNode + "']/Details")
   strErrorMsg=strErrorMsg & TCNode.text
  Next
 End If
 getFailureReason = strErrorMsg 
End Function

Solution - ActiveX component can't create object: 'TDApiOle80.TDConnection'

We can connect to ALM using 'TDApiOle80.TDConnection' object in VBscript as shown below:



Function CreateALMConnection(uRLALM,strUserName,strPassword,strDomain, strProject)
 Set objALMConnection = CreateObject("TDApiOle80.TDConnection")
        objQCConnection.InitConnectionEx uRLALM
        objQCConnection.Login strUserName, strPassword
        objQCConnection.Connect strDomain, strProject
  
  ''/* Write the required code for transaction with 
               '' ALM once the connection is created
   
  objQCConnection.Disconnect            
        objQCConnection.Logout
        objQCConnection.ReleaseConnection
        Set objQCConnection = Nothing
End Function 

Some of the useful code for interacting with ALM from VBScript can be found at below location:


Copying files from ALM to local machine


While running the script in 64 bit machine, error message 'ActiveX component can't create object: 'TDApiOle80.TDConnection' is displayed. In case you encounter such error, you can run the script from SysWow64 location in Windows as : 


C:\Windows\SysWOW64\cscript.exe scriptfilewithPath.vbs


From cscript.exe, the script will run successfully

Different Ways to exit from a QTP test: Using ExitTest, AOM and LoadandRunAction

In QTP, Framework should ensure that test is exited as soon test is failed, since there is no point in going forward with execution.
To ensure proper exit from QTP test, we can either use error handling using recovery scenario or vb script. In case of error handling using vbscript, we can exit a test at runtime in following ways.


Using ExitTest Statement

ExitTest statement exits a test once executed in script.But in scripts with functions called from other functions in different libraries and in case if there is multiple nesting of functions within different libraries, ExitTest statement on execution does not stop the test execution.
To understand this, suppose there is Test A and there are 4 different libraries(vbs files) f1,f2,f,3,f4  in which functions are stored and the action in Test A calls function from library f1 which further calls function from library f2 ans so on. In such cases, sometimes exitTest does not get executed and moves to next test without exiting the test.
To exit from test in scenario where ExitTest is not working properly, we can exit from test in below ways:


 Using QTP AOM

 Use following code to exit test in case exitstatement is not working.
Dim qtAppObj
Set qtAppObj = CreateObject("quicktest.application")
qtAppObj.Test.Stop

Using LoadandRunAction

Create a test with Action  Action1. In Action , only write ExitTest. Save the test.
Now in the test, where exitTest is not working properly, instead of ExitTest, write below code:

LoadandRunAction "c:\Test1","Action1"

Once this line of code is executed, QTP will exit the test.

Please go through the below posts for understanding of :

How to load and Associate Function libraries in QTP Test at runtime

Below are the various ways by which we can add/associate libraries with QTP tests so that functions in the libraries can be used within test.

ExecuteFile Statement 

      Executes the VBScript statements in the specified file. Functions, subroutines defined in the file are available from the global scope of the action's script.We cannot debug functions or statement contained in the file.

ExecuteFile "C:\BusinessLib.vbs”

Through QTP Interface 

      A library can be associated with a test so that the functions and subroutines, classes defined in the function library can be used .This can be achieved as follows:
      Navigate to File > Settings > Resources > Associate Function Library’ option in QTP. Add the required Libraries to the resources by clicking on + icon.

      Once function library is associated with the test.We can debug function in the function libraries and view function definition of the functions from the scripts.We can also define the priority of function library using up and down icon.

     
Associating Libraries with QTP tests

     

Using Load Function Library method

In  QTP 11, and onwards, We can dynamically load function library with the test using load function library. Libraries are released from test once completed. We can debug into function on calling library using LoadFunctionLibrary. The scope of the library is local to the action in which it is called.

Syntax: LoadFunctionLibrary “D:\TestLib.vbs”


We can add multiple files seperated by


Using Automation Object Model 

We can associate multiple libraries to QTP test using the below code. Also all the tests actions can use the functions from associated libraries.

strFilesNameCommaSeperated = "d:\test1.vbs,d:\test.vbs"
strTestName ="D:\Sample\Test1"
Call LoadLibrariesThroughAOM(strFilesNameCommaSeperated,strTestName)
Public Function LoadLibrariesThroughAOM(strFilesNameCommaSeperated,strTestName)
Set oqtapp = CreateObject("QuickTest.Application")
oqtapp.Launch
oqtapp.Visible = True
 strLibName = split(strFilesNameCommaSeperated,",")
'Open a test and associate a function library to the test
oqtapp.Open strTestName, False, False
Set oLib = oqtapp.Test.Settings.Resources.Libraries
 For i = 0 to ubound(strLibName)
                 LibName = strLibName(i)
                 ' If library is not already added, add the required library.
 
                If oLib.Find(LibName) = -1 Then
                         oLib.Add LibName, 1
                End If
 Next
oqtapp.Test.Save
                End Function


Understanding QTP Automation Object Model

QTP AOM (Automation Object Model) can be used to automate QTP Operations. Using the objects, methods, and properties exposed by the Quick Test automation object model,we can execute script, configure options settings,



Creating the QTP Object


Below lines of codes creates an instance of QTP,launches QTP and makes it visible.
Dim qtApp
Set qtApp = CreateObject("QuickTest.Application")
qtApp.Launch 'Start QTP
qtApp.Visible = True

If we want to execute on a remote computer, we use

Set qtApp = CreateObject("QuickTest.Application",”server”)

If we want to connect to QC from QTP AOM

 qtApp.TDConnection.connect “QC URL”,”Domain”,”Project”,”User”,”Pwd”


Working With QTP Tests using AOM


Open a new Test

Dim qtApp
Set qtApp = CreateObject("QuickTest.Application")
qtApp.Launch 'Start QTP
qtApp.Visible = True
qtApp.New

Opening an Existing Test

qtApp.Open “Test Path”,”True” ‘ Opens in read only mode.

Running a test through AOM

qtApp.Test.Run

Saving a test in QTP

If qtApp.Test.IsNew Then 
        qtApp.Test.SaveAs "C:\QTP\testqtp"
Else
        qtApp.Test.Save
End If

Generating script for QTP Settings and QTP Options for AOM


Set qtResultsOpt = CreateObject("QuickTest.RunResultsOptions") ' Create the Run Results Options object
qtResultsOpt.ResultsLocation =
"C:\Tests\Test1\Res1" ' Set the results location

qtTest.Run qtResultsOpt
Set qtResultsOpt = CreateObject("QuickTest.RunResultsOptions") ' Create the Run Results Options object
qtResultsOpt.ResultsLocation =
"C:\Tests\Test1\Res1" ' Set the results location

qtTest.Run qtResultsOpt

Defining Settings in QTP

To know, how settings are defined and QTP object is launched, and settings are defined using AOM, Go to File>Settings>Properties and click on Generate Script. This will generate a script with all the default setting parameters

Default Setting script


The Content of the script will be as follows:

Dim App 'As Application
Set App = CreateObject("QuickTest.Application")
App.Launch
App.Visible = True
App.Test.Settings.Launchers("Web").Active = False
App.Test.Settings.Launchers("Web").Browser = "IE"
App.Test.Settings.Launchers("Web").Address = "http://www.rediff.com"
App.Test.Settings.Launchers("Web").CloseOnExit = True
App.Test.Settings.Launchers("Windows Applications").Active = True
App.Test.Settings.Launchers("Windows Applications").Applications.RemoveAll
App.Test.Settings.Launchers("Windows Applications").RecordOnQTDescendants = True
App.Test.Settings.Launchers("Windows Applications").RecordOnExplorerDescendants = False
App.Test.Settings.Launchers("Windows Applications").RecordOnSpecifiedApplications = True
App.Test.Settings.Run.IterationMode = "rngAll"
App.Test.Settings.Run.StartIteration = 1
App.Test.Settings.Run.EndIteration = 1
App.Test.Settings.Run.ObjectSyncTimeOut = 20000
App.Test.Settings.Run.DisableSmartIdentification = False
App.Test.Settings.Run.OnError = "Dialog"
App.Test.Settings.Resources.DataTablePath = "<Default>"
App.Test.Settings.Resources.Libraries.RemoveAll
App.Test.Settings.Web.BrowserNavigationTimeout = 60000
App.Test.Settings.Web.ActiveScreenAccess.UserName = ""
App.Test.Settings.Web.ActiveScreenAccess.Password = ""


Defining Options in QTP


To know the current options settings in QTP, we can generate a script similar to Settings as defined above through Tools>Options>General and clicking on generate scripts.


















Dim App 'As Application
Set App = CreateObject("QuickTest.Application")
App.Launch
App.Visible = True
App.Options.DisableVORecognition = False
App.Options.AutoGenerateWith = False
App.Options.WithGenerationLevel = 2
App.Options.TimeToActivateWinAfterPoint = 500
App.Options.SaveLoadAndMonitorData = True
App.Options.Run.RunMode = "Fast"
App.Options.Run.ViewResults = True
App.Options.Run.StepExecutionDelay = 0
App.Options.Run.MovieCaptureForTestResults = "Never"
App.Options.Web.AddToPageLoadTime = 10
App.Options.Web.RecordCoordinates = False
App.Options.Web.RecordMouseDownAndUpAsClick = False
App.Options.Web.RecordAllNavigations = False
App.Options.Web.RecordByWinMouseEvents = ""
App.Options.Web.BrowserCleanup = False
App.Options.Web.RunOnlyClick = False
App.Options.Web.RunMouseByEvents = True
App.Options.Web.RunUsingSourceIndex = True
App.Options.Web.EnableBrowserResize = True
App.Options.Web.PageCreationMode = "URL"
App.Options.Web.CreatePageUsingUserData = "Get Post"
App.Options.Web.CreatePageUsingNonUserData = ""
App.Options.Web.CreatePageUsingAdditionalInfo = True
App.Options.Web.FrameCreationMode = "URL"
App.Options.Web.CreateFrameUsingUserData = "Get Post"
App.Options.Web.CreateFrameUsingNonUserData = ""
App.Options.Web.CreateFrameUsingAdditionalInfo = True
App.Options.WindowsApps.AttachedTextRadius = 35
App.Options.WindowsApps.AttachedTextArea = "TopLeft"
App.Options.WindowsApps.ExpandMenuToRetrieveProperties = True
App.Options.WindowsApps.NonUniqueListItemRecordMode = "ByName"
App.Options.WindowsApps.RecordOwnerDrawnButtonAs = "PushButtons"
App.Options.WindowsApps.ForceEnumChildWindows = 0
App.Options.WindowsApps.ClickEditBeforeSetText = 0
App.Options.WindowsApps.VerifyMenuInitEvent = 0
App.Options.TextRecognitionOrder = "APIThenOCR"
App.Folders.RemoveAll


Object Repositories in QTP:Understanding Types and Collection Object.


Object Repository stores all the objects learned in the application. An Object repository is automatically created when we record in the application. Object can also be added in object repository through object spy and Navigate and Learn objects.

Following are important points to remember about object repositories:

  • Objects are stored in tree structure in OR with child objects linked to parent objects.
  • Objects in Local OR and shared OR can be accessed/modified through Object Repository window and Object repository manager window respectively.
  • Objects in OR can be added through:
o    Recording mode
o    Active screen
o    Using Object Spy
o    Using Navigate and Learn through Object repository window.
  • Objects can be added with expected properties defined manually in OR. This is useful in case application is not ready, but we know the expected property for objects.
  • Copying or moving an object to be a child of a bottom-level object in the object hierarchy is not allowed.
  • Property value and name of object in object repository can be modified.
  • Modifying the name of a test object in the local object repository is automatically updated in both the Keyword View and the Expert View for all occurrences of the test object.
  • We can highlight objects from OR in application.
  • Object from object repositories can be dragged and drop in the expert view. Hierarchy Tree of the object is visible in expert view on dragging object from OR.


There are two types of Object Repositories:


1. Local Repository

Objects are automatically added in Local Object Repository once they are learned from the application.

Following are important points to remember about Local Object Repository:

  • If an object with the same name is located in both the local object repository and in a shared object repository associated with the same action, the action uses the local object definition.
  • Local Object Repository is associated with the action in which it was created. You cannot associate Local object repository with multiple actions. Due to this, they are useful mainly in single action.
  • If child objects are moved from shared OR to local OR, parent objects are also added to Local OR.


2. Shared Object Repository


A shared object repository stores objects in a file that can be accessed by multiple tests (in read-only mode).

Following are important points to remember about Local Object Repository:

  • Same Shared Object repository can be added for multiple actions.
  • Shared OR can be dynamically associated with tests and multiple actions.
  • Shared OS is saved with extension .tsr
  • Objects from local OR can be exported to shared OR.
  • An Action can have multiple Shared object repository associated.
  • A shared repository can be edited by one person at a time and is locked for other user
  • Using OR comparison tool, we can compare the objects in 2 different shared OR
  • Using Object repositories Merge tool, we can merge two shared OR and create a new OR with objects from both the OR’s.

Associating Repositories with Action

We can associate object repositories with action in following ways:

Through QTP Interface


Navigate to Resources>Associate Repositories. Click on + icon and select repositories. Note we can add shared object repository only. Next Select Actions from available Actions and move required actions to Associated Actions.



Associating Repositories with Actions
























Using Object Repositories collection


We can add object repositories using ObjectRepositories Collection

Below code snippet shows how to add ObjectRepositories using QTP AOM

Public Function func_AddORToTest(TestName, ActionName, ORName)
''Create an object of qtp
Set qtApp = CreateObject("QuickTest.Application")
qtApp.Launch
qtApp.Visible = True

qtApp.Open TestName
Set qtRepositories = qtApp.Test.Actions(ActionName).ObjectRepositories


' Add MainApp.tsr if it's not already in the collection
If qtRepositories.Find(ORName) = -1 Then ' If the repository cannot be found in the collection
qtRepositories.Add ORName, 1 ' Add the repository to the collection
End If
'Save the test and close QuickTest
qtApp.Test.Save
qtApp.Quit 


Set qtRepositories = Nothing
Set qtApp = Nothing

End Function