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

Batch file to delete all files from folder

Below code shows how to delete all files from a folder matching the specific criteria.

FORFILES /p "E:\test\Result" /s /m *.* /D -5 /C "cmd /c del *.* /F /Q"

The above code will delete all files in the folder "E:\test\Result" recursively in the sub folder matching all the files which are older than 5 days.

No pop-up and prompt will be displayed and file will be deleted

VBScript code to convert Excel data to HTML format


This article explains the code to convert content of an excel file into html code. This can be useful for better representation of excel data in html format.

Code to convert Excel data to HTML format

''strWbk - Full path of the excel workbook
''strWsheetName - Name of the worksheet
'' strHTMLFile - Name of the html file with path
Public Function CreateHTMLFromExcel(strWbk,strWsheetName,strHTMLFile)
Set oExcel = Createobject("Excel.Application")
oExcel.visible = false
Set objExcelWB = oExcel.Workbooks.Open(strWbkPath)
Set objExcelWS = objExcelWB.Worksheets(strWsheetName)
'Getting the rows and column count
 strColumnCount = objExcelWS.UsedRange.Columns.Count
 strTotRows = objExcelWS.UsedRange.Rows.Count
strTable = "<table border=""""2"""">"
'Create html table based on content of the excel file
 For j=1 to strTotRows
  strTable = strTable & "<tr>"
  For i=1 to strColumnCount
    strData = Trim(objExcelWS.Cells(j,i))
    strTable= strTable & "<td>"& strData &"</td>"
  Next
  strTable =strTable & "</tr>"
 Next
 strTable = strTable & "</table>"
 set objFSO=Createobject("scripting.FileSystemObject")
 set objtxt = objFSO.createTextFile(strHTMLFile)
    objtxt.write(strTable)
'Closing the workbook
 objExcelWB.Close
 set objFSO =nothing
End Function

Ordinal Identifier in QTP

While learning the objects, QTP tries to identify objects based on the mandatory and assistive properties of the object. In case the above properties are insufficient to uniquely identify the object. QTP uses the ordinal identifier properties to uniquely identify the object together with the madatory and assistive properties.


There are three type of Ordinal Identifier in QTP which are assigned as numeric integer value for the object based on the order occurrence of object in the browser.


The three types of ordinal identifier are described below:



Ordinal Identifier

Description

 Index Based

Based on the object in the window, An index value is assigned to object based on existence in the source code. Index value starts from 0.

Location Based 

The Location property is based on location of object, works vertically from top to bottom and then from left to right. value starts from 0.

Creation Time

The Creation Time property is used for browser objects mainly and used to identify multiple browsers based on the time the browser/page was open. Value starts from 0

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

Code to get title of all open browsers in QTP/UFT

We can get titles of all the open browser open using descriptive programming in QTP as explained in the code below:


Function GettitleAllbrowsers()
GettitleAllbrowsers = ""
Set objBrowser = Description.Create
objBrowser("micclass").Value = "Browser"
''Get all browsers instances in ObjBrowserLst 
Set objBrowserLst= Desktop.ChildObjects(objBrowser)
''Get the count of all the browsers open
browsercnt = objBrowserLst.count
For i=0 to objBrowserLst.count-1  
'Store title of the Page in a variable 
GettitleAllbrowsers = GettitleAllbrowsers + ">"+objBrowserLst(i).GetROProperty("title") 
Next 
Set objBrowser = nothing
Set objBrowser = nothing
End Function


For further manipulating the browser details using descriptive programming. Please go through the below articles:


Code to close multiple browsers except Quality Center/ALM in UFT/QTP?

How to close the IE browsers and Internet Explorer not responding windows forecefully -VBScript

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




Simulating Keyboard and mouse operations in UFT using settings.replay type

In QTP, We can replicate device events, i.e keyboard and mouse operation using the below line of code.

Setting.WebPackage("ReplayType") = 2

By default, value of the Setting is 1, in which UFT interacts with application using the browser through DOM.

Setting.WebPackage("ReplayType") = 1

In case, you are not able to perform click or operation on an element in the page, please give a try by providing setting:

 Setting.WebPackage("ReplayType") =2

Useful Batch file commands

Batch files help user to execute series of commands in the batch file. We can execute large number of commands in one go using bat file.

Some useful batch commands:

@echo off does not echo the text post the command and only displayes the execution result

@echo on the text post the command and only displays the execution result

Pause- the batch file execution is halted until further intervention of user by pressing keys.

CALL - calling one batch file from another batch file

cd -  Change directory

cls - clean the window

copy -copy files from source to destination

DIR - List of directory and files

ERASE - delete files

FC - Compares files
 
IF - Conditional statement

mkdir - Make a new directory/folder

move - move files or folder

ping - Check TCP/IP connection to a remote IP address

rmdir - remove folder/directory

SC - Managing services

set - manipulate environment variable 

taskkill - kills an active process

taslist - List active processes

REM - remark statement
Arguments %1….. – This is the first argument to be provided from the
 command prompt as parameter for the batch command.


Reference: http://www.robvanderwoude.com/batchcommands.php


Starting with batch files:

Let us take a simple example of using batch file to display Create a new file with extension as .bat. Suppose we need to compare two text files. The content of batch file for this will look like


@echo off

Fc %1 %2 /n>%3

Pause


To execute this bat file, we have to write in command prompt  as:

D:\new.bat d:\testsrc.txt d:\testdest.txt d:\testlog.txt

Renaming all/specific subfolders in a folder using vbscript FSO

In this post, how to rename all the subfolders in a folder using vbscript is explained

  • Renaming all sub folders in a folder removing spaces from the file

call RemoveblankSpace_Subfolders("D:\TextTest")

 ''strbasefoldername - Folder Path in which file needs to be replaced
 Public Function RemoveblankSpace_Subfolders(strbasefoldername)
 On error resume next
 Dim objFSO
 Set objFSO = CreateObject("Scripting.FileSystemObject") 
    Dim objFolder 
    For Each objSubFolder In objFSO.GetFolder(strbasefoldername).SubFolders
     FlderName = objSubFolder.Name
  FlderName = replace(FlderName," ","")
  objSubFolder.Name = FlderName
    Next 
    Set objSubFolderFolder = Nothing 
    Set objFSO = Nothing 
End Function

  • Rename specific subfolder in a folder using vbscript


call Rename_Subfolders("D:\TextTest","es","twist",false,"test")

'' strbasefoldername - Folder Path in which file needs to be replaced
'' strFindtext - text in the folder name that needs to be replaced
'' strReplaceText - new text to replace the existing test
'' boolAllFlders - boolean flag to indicate if all the subfolder needs to be renamed or
'' specific folders needs to be renamed
'' OnlyfoldersWithText - replace only folder with specific text. will consider only if
'' boolAllFlders =true
 Public Function Rename_Subfolders(strbasefoldername,strFindtext,strReplaceText,boolAllFlders,OnlyfoldersWithText)
 On error resume next
 Dim objFSO
 Set objFSO = CreateObject("Scripting.FileSystemObject") 
    Dim objFolder
    For Each objSubFolder In objFSO.GetFolder(strbasefoldername).SubFolders
 FlderName = objSubFolder.Name
  if boolAllFlders = false then
   if(instr(1,FlderName,OnlyfoldersWithText)>0) then
    FlderName = replace(FlderName,strFindtext,strReplaceText)
    objSubFolder.Name = FlderName
   End If
  else
    FlderName = replace(FlderName,strFindtext,strReplaceText)
    objSubFolder.Name = FlderName
  End If
    Next 
    Set objSubFolderFolder = Nothing 
    Set objFSO = Nothing 
End Function

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

Manipulation XML using XPath for VBScript/UFT

This article explains how to extract information from an xml file based on the element xpath using Microsoft.XMLDOM and VBSript. You can try using the code as shown below.


''---------------------------------------------------------------------------------
'' Step 1 : Copy the content removing comments in a file and save the file
''----------------------------------------------------------------------------------

'' --------------File Content ------------------------------------------------------
''XMLTextFile = "<books><name>mybook</name><price>50</price><Author rating="high">matt</Author>
''<name>his book</name><price>150</price><Author rating="low">henry</Author>
''<name>twist</name><price>550</price><Author rating="high">henry</Author></books>"

''-------------Call the functions with Parameters------------------------------------
msgbox getXMLTextFileValue("d:\testdta.xml","//price")
msgbox getXMLTextFileValue("d:\testdta.xml","//Author[@rating='high']")
msgbox getxmlAttributeValue("d:\testdta.xml","//Author","rating")
call getAllNodeValues("d:\testdta.xml","//Author")
''-----------------------------------------------------------------------------------

'' Function 1 - Reading the node text
''Arguments - FileName and xpath of node

''-----------------------------------------------------------------------------------
function getXMLTextFileValue(XMLTextFile,NodeXpath)
Set objXML = CreateObject("Microsoft.XMLDOM")

objXML.async = False
objXML.resolveExternals = False
objXML.validateOnParse = False
getXMLTextFileValue = ""
boolxmlParse = objXML.load(XMLTextFile)
if(boolxmlParse) then
 objXML.setProperty "SelectionLanguage", "XPath"
 set objXML_node = objXML.selectSingleNode(NodeXpath)
        getXMLTextFileValue = objXML_node.text
 else
 msgbox "issue in xml file"
End If
End Function

''-----------------------------------------------------------------------------------

'' Function 1 - Reading the node attribute value
''Arguments - FileName and xpath of node. attribute Name of which value is to be returned

''-----------------------------------------------------------------------------------


function getxmlAttributeValue(XMLTextFile,NodeXpath, attributeName)
Set objXML = CreateObject("Microsoft.XMLDOM")

objXML.async = False
objXML.resolveExternals = False
objXML.validateOnParse = False
getxmlAttributeValue = ""
boolxmlParse = objXML.load(XMLTextFile)
if(boolxmlParse) then
 objXML.setProperty "SelectionLanguage", "XPath"
 set objXML_node = objXML.selectSingleNode(NodeXpath)
        getxmlAttributeValue = objXML_node.getAttribute(attributeName)
 else
 msgbox "issue in xml file"
End If
End Function

''-----------------------------------------------------------------------------------

'' Function 1 - Reading the value of all the matching nodes
''Arguments - FileName and xpath of node.

''-----------------------------------------------------------------------------------

function getAllNodeValues(XMLTextFile,NodeXpath)
Set objXML = CreateObject("Microsoft.XMLDOM")

objXML.async = False
objXML.resolveExternals = False
objXML.validateOnParse = False

boolxmlParse = objXML.load(XMLTextFile)
if(boolxmlParse) then
 objXML.setProperty "SelectionLanguage", "XPath"
 set objXML_node = objXML.selectNodes(NodeXpath)
        for each nodet in objXML_node
  msgbox nodet.text
 Next
End If
End Function

VBSript Code: copying text from HTML webPage to Local


In this article, Code to copy html content from a web html page to local machine is explained. You can try the code, saving it as vbs file and running. 

''Create a file using scripting.fileSystemObject
Set objFSO=CreateObject("Scripting.FileSystemObject")
''Provide the Path of html file
testfilePath="d:/testing.html"
'' Create html file using filesystem object
Set objFile = objFSO.CreateTextFile(testfilePath,True)

''Define the Page URL from which html is to be extracted
WebURL="http://seleniumbites.blogspot.in/2016/12/install-jenkins-as-windows-service.html"
Set httpcontent = CreateObject("Microsoft.XmlHttp")

On Error Resume Next
httpcontent.open "GET", URL, False
httpcontent.send ""
if err.Number = 0 Then
     objFile.Write httpcontent.responseText  
Else
     msgbox err.description
End If
Set httpcontent = Nothing
objFile.Close